给我一个用Pthreads实现直方图统计的代码
时间: 2024-04-10 22:27:49 浏览: 18
当然可以!以下是一个使用Pthreads库实现直方图统计的简单代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 4
#define NUM_BINS 10
int data[] = {2, 3, 5, 2, 6, 8, 4, 5, 7, 1, 4, 9, 3, 2, 5, 8};
int histogram[NUM_BINS] = {0};
pthread_mutex_t mutex;
void* calculate_histogram(void* arg) {
int thread_id = *(int*)arg;
int start = thread_id * (sizeof(data) / sizeof(data[0])) / NUM_THREADS;
int end = (thread_id + 1) * (sizeof(data) / sizeof(data[0])) / NUM_THREADS;
for (int i = start; i < end; i++) {
pthread_mutex_lock(&mutex);
histogram[data[i]]++;
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];
pthread_mutex_init(&mutex, NULL);
for (int i = 0; i < NUM_THREADS; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, calculate_histogram, &thread_ids[i]);
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&mutex);
printf("Histogram:\n");
for (int i = 0; i < NUM_BINS; i++) {
printf("%d: %d\n", i, histogram[i]);
}
return 0;
}
```
这个代码示例中,我们使用了4个线程(可以根据需要调整`NUM_THREADS`的值),并将数据分成了4个部分,每个线程负责处理其中一个部分。在计算直方图时,我们使用互斥锁来保证对直方图数组的访问是线程安全的。
希望这个示例对你有帮助!如果你有任何疑问,请随时提问。