使用C语言编写的二分查找程序,使用pthread进行多线程处理

2023年 8月 29日 44.8k 0

使用C语言编写的二分查找程序,使用pthread进行多线程处理

#include
#define MAX 16
#define MAX_THREAD 4
using namespace std;
//place arr, key and other variables as global to access from different thread
int arr[] = { 1, 6, 8, 11, 13, 14, 15, 19, 21, 23, 26, 28, 31, 65, 108, 220 };
int key = 31;
bool found = false;
int part = 0;
void* binary_search(void* arg) {
// There are four threads, each will take 1/4th part of the list
int thread_part = part++;
int mid;
int start = thread_part * (MAX / 4); //set start and end using the thread part
int end = (thread_part + 1) * (MAX / 4);
// search for the key until low < high
// or key is found in any portion of array
while (start key)
end = mid - 1;
else
start = mid + 1;
}
}
main() {
pthread_t threads[MAX_THREAD];
for (int i = 0; i < MAX_THREAD; i++)
pthread_create(&threads[i], NULL, binary_search, (void*)NULL);
for (int i = 0; i < MAX_THREAD; i++)
pthread_join(threads[i], NULL); //wait, to join with the main thread
if (found)
cout

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论