目前我正在学习 Linux 上的 POSIX 线程。以下示例计算整数数组中有多少个 3(int),它在 CentOS 6.5 上返回正确答案,但在 macOS 10.12.4 上返回错误答案。
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#define thread_num 16
#define MB 1024 * 1024
int *array;
int length; //array length
int count;
int t; //number of thread
void *count3s_thread(void* id);
pthread_mutex_t myMutex;//create a mutex
int main()
{
//initialize mutex
if (pthread_mutex_init(&myMutex, NULL) != 0)
printf("Mutex init failed!\n");
int i;
int tid[thread_num];
pthread_t threads[thread_num];
length = 64 * MB;
array = malloc(length * 4);
//initialize the array
//when i is an odd number, array[i] = 4
//when i is an even number, array[i] = 3
for (i = 0; i < length; i++)
array[i] = i % 2 ? 4 : 3;
for (t = 0; t < thread_num; t++)
{
count = 0;
tid[t]=t;
int err = pthread_create(&(threads[t]), NULL, count3s_thread,&(tid[t]) );
if (err)
{
printf("create thread error!\n");
return 0;
}
}
for (t = 1; t < thread_num; t++)
pthread_join(threads[t], NULL);
printf("Total count= %d \n",count);
pthread_mutex_destroy(&myMutex);
return 0;
}
void *count3s_thread(void* id)
{
//printf("id from count3s_thread = %d\n", *(int *)id);
int length_per_thread = length / thread_num; //length of every thread
int start = *(int *)id * length_per_thread;
int i;
for (i = start; i < start + length_per_thread; i++)
{
if (array[i] == 3)
{
pthread_mutex_lock(&myMutex);
count++;
pthread_mutex_unlock(&myMutex);
}
}
return NULL;
}
答案应该是 64 * 1024 * 1024/2 = 67,108,864/2 = 33,554,432。但 macOS 上的答案永远不会是正确的。我使用以下选项编译代码:
gcc mutex-demo.c -lpthread -o mutex-demo
我已尝试解决 this link 之后的问题.但是,我在初始化 pthread mutex 时仍然得到错误的答案。我错过了什么吗?
PS:我已经尝试过 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
或 pthread_mutex_init( &mutex, NULL)
但在 macOS 上运行的程序仍然返回错误答案。
非常感谢!
最佳答案
pthread_create
之前的行 count = 0;
将 count
设置为 0
,因此您重置该值count
而线程递增它们。删除此行。当主线程在线程开始计数之前完成 pthread_create
时,它可能适用于其他系统。
我已经在评论中提到了:
for (t = 1; t < thread_num; t++)
pthread_join(threads[t], NULL);
应该是
for (t = 0; t < thread_num; t++)
// ^
pthread_join(threads[t], NULL);
否则你不会等待第一个线程完成。
关于c - pthread mutex 在 macOS 上无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43820721/