#include <stdio.h>\n#include <stdlib.h>\n#include <pthread.h>\n\n#define NUM_THREADS 5\n#define HASH_SIZE 10\n\ntypedef struct {\n int id;\n int* hash_table;\n int target;\n int result;\n} ThreadData;\n\nvoid* hash_search(void* thread_data) {\n ThreadData* data = (ThreadData*)thread_data;\n int* hash_table = data->hash_table;\n int target = data->target;\n int result = -1;\n\n for (int i = data->id; i < HASH_SIZE; i += NUM_THREADS) {\n if (hash_table[i] == target) {\n result = i;\n break;\n }\n }\n\n data->result = result;\n pthread_exit(NULL);\n}\n\nint main() {\n int hash_table[HASH_SIZE] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};\n int target = 14;\n pthread_t threads[NUM_THREADS];\n ThreadData thread_data[NUM_THREADS];\n\n for (int i = 0; i < NUM_THREADS; i++) {\n thread_data[i].id = i;\n thread_data[i].hash_table = hash_table;\n thread_data[i].target = target;\n thread_data[i].result = -1;\n pthread_create(&threads[i], NULL, hash_search, (void*)&thread_data[i]);\n }\n\n for (int i = 0; i < NUM_THREADS; i++) {\n pthread_join(threads[i], NULL);\n }\n\n int result = -1;\n for (int i = 0; i < NUM_THREADS; i++) {\n if (thread_data[i].result != -1) {\n result = thread_data[i].result;\n break;\n }\n }\n\n if (result != -1) {\n printf("Target found at index %d.\n", result);\n } else {\n printf("Target not found.\n");\n }\n\n return 0;\n}\n

使用 Pthreads 实现多线程哈希查找算法 - 代码示例

原文地址: https://www.cveoy.top/t/topic/pWCx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录