我试图创建 2 个线程并调用相同的函数,该函数从 for 循环递增计数器“count”。但是每次我运行这段代码时,计数器的值都是不同的。当线程递增全局静态变量“count”但值仍然不同时,我尝试使用互斥锁在线程之间进行同步。
static int count;
pthread_mutex_t count_mutex;
void increment()
{
pthread_mutex_lock(&count_mutex);
count++;
pthread_mutex_unlock(&count_mutex);
}
void *myThreadFun1(void *var)
{
printf("Thread1\n");
for(int i=0; i< 10000;i++)
{
increment();
}
return;
}
int main()
{
pthread_t tid1;
pthread_t tid2;
pthread_create(&tid1, NULL, myThreadFun1, NULL);
// sleep(1);
pthread_create(&tid2, NULL, myThreadFun1, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("\n%d",count);
exit(0);
}
如果我不在线程之间休眠,输出永远不会是 20000。
在 java 中我们可以使用“synchronized”关键字,但如何在 C 中实现相同的关键字?
最佳答案
pthread_mutex_t 在使用前需要初始化。它必须开始解锁和解除绑定(bind)。有一个调用 pthread_mutex_init(&theMutex) 可以做到这一点,或者可以为静态初始化分配一个预定义的值:PTHREAD_MUTEX_INITIALIZER
关于c - 使用互斥量的 pthread 同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43554134/