pthread mutex在macOS上无法正常工作
目前我正在学习Linux上的POSIX线程。以下示例计算整数数组中有多少个3(int),在CentOS 6.5上返回正确答案,但在macOS 10.12.4上返回错误答案pthread mutex在macOS上无法正常工作,c,linux,macos,pthreads,mutex,C,Linux,Macos,Pthreads,Mutex,目前我正在学习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
#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;
}
我试着解决下面的问题。然而,在初始化pthread互斥体时,我仍然得到了一个错误的答案。我错过什么了吗
PS:我尝试了pthread\u mutex\u t mutex=pthread\u mutex\u初始值设定项
或pthread\u mutex\u init(&mutex,NULL)
但在macOS上运行的程序仍然返回错误的答案
提前谢谢 行
计数=0在pthread\u create
之前,code>将count
设置为0
,因此在线程递增时重置count
的值。拆下这条线。当主线程在线程开始计数之前完成pthread\u create
时,它可能在其他系统上工作
我在评论中已经提到:
for (t = 1; t < thread_num; t++)
pthread_join(threads[t], NULL);
for(t=1;t
应该是
for (t = 0; t < thread_num; t++)
// ^
pthread_join(threads[t], NULL);
for(t=0;t
否则,您将不会等待第一个线程完成。for
pthread\u join的循环从1
开始,而不是0
。如果在不使用pthread\u create
的情况下调用函数,您是否得到了正确的值?我没有得到你的期望值:谢谢!在我删除行count=0之后
并在pthread_join循环中设置t=0
,最终结果是正确的。然而,我还有一个问题:为什么pthread\u create
会自动将count
设置为0
?函数pthread\u create
和count3s\u thread
都没有可以将count
设置为0
的语句count
是一个全局变量,它是0
初始化的。哦,我刚刚忘记了C中的全局变量将自动初始化为0
。不管怎样,谢谢你告诉我这么多。
for (t = 0; t < thread_num; t++)
// ^
pthread_join(threads[t], NULL);