使用pthreads实现哈希查找算法的代码
以下是使用pthread来实现哈希查找算法的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
#define HASH_SIZE 10
typedef struct {
int id;
int* hash_table;
int target;
int result;
} ThreadData;
void* hash_search(void* thread_data) {
ThreadData* data = (ThreadData*)thread_data;
int* hash_table = data->hash_table;
int target = data->target;
int result = -1;
for (int i = data->id; i < HASH_SIZE; i += NUM_THREADS) {
if (hash_table[i] == target) {
result = i;
break;
}
}
data->result = result;
pthread_exit(NULL);
}
int main() {
int hash_table[HASH_SIZE] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int target = 14;
pthread_t threads[NUM_THREADS];
ThreadData thread_data[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
thread_data[i].id = i;
thread_data[i].hash_table = hash_table;
thread_data[i].target = target;
thread_data[i].result = -1;
pthread_create(&threads[i], NULL, hash_search, (void*)&thread_data[i]);
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
int result = -1;
for (int i = 0; i < NUM_THREADS; i++) {
if (thread_data[i].result != -1) {
result = thread_data[i].result;
break;
}
}
if (result != -1) {
printf("Target found at index %d.\n", result);
} else {
printf("Target not found.\n");
}
return 0;
}
在此示例中,我们定义了一个 ThreadData 结构来存储每个线程的数据,包括线程ID、哈希表、目标值和结果。hash_search 函数是每个线程执行的实际函数,它在哈希表中查找目标值。每个线程都处理哈希表的一部分,通过循环来跳过其他线程已经处理过的元素。如果找到目标值,将结果设置为对应的索引;否则,结果保持为 -1。
在主函数中,我们创建了多个线程,并将每个线程的数据传递给 hash_search 函数。然后,我们等待所有线程完成执行,检查每个线程的结果,并输出相应的信息。
请注意,此示例中的哈希表和目标值是硬编码的,您可以根据自己的需求进行更改。另外,此代码示例仅用于演示目的,可能需要根据实际情况进行修改和优化
原文地址: http://www.cveoy.top/t/topic/id1e 著作权归作者所有。请勿转载和采集!