【发布时间】:2020-01-25 19:11:03
【问题描述】:
我正在学习 POSIX pthreads,在使用互斥锁时,我开始得到一个奇怪的输出。
每次我运行代码时,它都会输出一个随机数,而我希望它输出0。我检查了代码,但我无法弄清楚它发生的原因,所以如果有人能向我解释到底出了什么问题,我将不胜感激。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int num = 0;
pthread_mutex_t mutex;
void* add(void* args)
{
int sign = *(int*) args;
for(int i = 0; i < 100; i++)
{
pthread_mutex_lock(&mutex);
num += sign;
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
return NULL;
}
int main()
{
pthread_t pool[1000];
int plus = +1;
int minus = -1;
pthread_mutex_init(&mutex, NULL);
for(int i = 0; i < 500; i++)
pthread_create(&pool[i], NULL, add, &plus);
for(int i = 500; i < 1000; i++)
pthread_create(&pool[i], NULL, add, &minus);
for(int i = 0; i < 1000; i++)
pthread_join(pool[i], NULL);
printf("%d", num);
return 0;
}
【问题讨论】:
-
在您假设互斥锁不起作用之前,请尝试使用合理的线程数(例如,每边 100、50)。根据平台的不同,单个进程中的一千个线程是一个延伸。而且由于这段代码中绝对没有任何错误检查,你真的不知道问题是什么。它可能与互斥锁无关。 pthread 函数的那些返回值意味着什么;使用它们。
-
@yxor
pthread_create()失败后errno的值是多少? -
@yxor 提交错误报告。 The proper
errnovalue in that case should beEAGAIN. -
注意:大多数操作系统都设置为极大地限制线程数。
-
The proper way to initialize a pthread_mutex_t- 用pthread_mutex_init初始化互斥锁同样有效。so when calling pthread_join(), the code can skip those entries- 不,假设“0”对pthread_t具有特殊含义,并且在pthread_join中具有特殊含义,只是不可移植,并且对实现进行了假设。pthread_t是任何用于标识线程的抽象类型,the specification 没有多说什么。为了便于携带,只需使用另一个布尔数组。