在C中使用多线程进行线性搜索
在这里,我们将看到如何应用多线程概念来搜索数组中的一个元素。这里的方法非常简单。我们将创建一些线程,然后将数组划分为不同的部分。不同的线程将搜索不同的部分。之后,找到元素后,启用标志以标识此元素。
示例
#include <stdio.h>
#include <pthread.h>
#define MAX 16
#define THREAD_MAX 4
int 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 not
int 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 < ((num + 1) * (MAX / 4)); i++){
if (array[i] == key)
flag = 1; //set flag if key is found
}
}
int main() {
pthread_t thread[THREAD_MAX];
for (int i = 0; i < THREAD_MAX; i++) { //create multiple threads
pthread_create(&thread[i], NULL, ThreadSearch, (void*)NULL);
}
for (int i = 0; i < THREAD_MAX; i++) {
pthread_join(thread[i], NULL); //wait untill all of the threads are completed
}
if (flag == 1)
printf("Key element is found\n");
else
printf("Key element is not present\n");
}输出结果
$ gcc 1249.Thread_search.cpp -lpthread $ ./a.out Key element is found
热门推荐
4 足球队祝福语简短
8 怎么说祝福语简短
10 祝球员赛前祝福语简短
11 理科元旦祝福语大全简短
12 生日祝福语 简短独特老弟
13 古诗生日祝福语简短独特
14 学生开学季祝福语简短
15 杨奕老师祝福语简短
16 结婚祝福语简短精辟 兄弟
17 婚庆花篮祝福语简短大气
18 中秋妈妈生日祝福语简短