这里我们将看到如何应用多线程概念来搜索数组中的一个元素。这里的方法非常简单。我们将创建一些线程,然后将数组分成不同的部分。不同的线程会在不同的部分进行搜索。之后,当找到该元素时,启用标志来识别该元素。
示例
#include #include #define MAX 16#define THREAD_MAX 4int array[MAX] = { 1, 5, 7, 10, 12, 14, 15, 18, 20, 22, 25, 27, 30, 64, 110, 220 };int key = 18;int flag = 0; //flag to indicate that item is found in the array or notint current_thread = 0;void* ThreadSearch(void* args) { //This is linear search function. It will be running using all threads int num = current_thread++; for (int i = num * (MAX / 4); i"); else printf("Key element is not present
");}
登录后复制
输出
$ gcc 1249.Thread_search.cpp -lpthread$ ./a.outKey element is found
登录后复制
以上就是在C语言中使用多线程进行线性搜索的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2583369.html