C语言 在C中使用互斥锁同步两个pthread
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14840135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Synchronizing two pthreads using mutex in C
提问by Codebox
Need help with synchronizing two threads with mutex. Iam new to C and mutexes and Im not sure what to do here. The code has two threads that counts to ten and prints out each number, but is not synch, so it will not print synchronized, it is half synched. Means that i only get trouble in the end, sometimes it prints 8..9..11, 8..9..10..10 and so on.
需要有关使用互斥锁同步两个线程的帮助。我是 C 和互斥体的新手,我不确定在这里做什么。代码有两个线程,计数到十并打印出每个数字,但不是同步的,所以它不会打印同步,它是半同步的。意味着我最终只会遇到麻烦,有时它会打印 8..9..11、8..9..10..10 等等。
I cannot make changes to the raw code, if you take away the lines about mutexes, that is the raw code. I can only add lines about mutexes.
我无法对原始代码进行更改,如果您删除有关互斥锁的行,那就是原始代码。我只能添加有关互斥锁的行。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
pthread_mutex_t mutex;
int g_ant = 0;
void *writeloop(void *arg) {
while(g_ant < 10) {
pthread_mutex_lock(&mutex);
g_ant++;
usleep(rand()%10);
printf("%d\n", g_ant);
pthread_mutex_unlock(&mutex);
}
exit(0);
}
int main(void)
{
pthread_t tid;
pthread_mutex_init(&mutex, NULL);
pthread_create(&tid, NULL, writeloop, NULL);
writeloop(NULL);
pthread_join(tid, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
采纳答案by user7116
With the condition outside your mutex you may not be receiving the correct values. A guaranteed way to ensure the loop operates in-order would be the following change to writeloop:
在互斥锁之外的条件下,您可能无法收到正确的值。确保循环按顺序运行的有保证的方法是对 进行以下更改writeloop:
void writeloop(void *arg) {
while (g_ant < 10) {
pthread_mutex_lock(&mutex);
if (g_ant >= 10) {
pthread_mutex_unlock(&mutex);
break;
}
g_ant++;
usleep(rand()%10);
printf("%d\n", g_ant);
pthread_mutex_unlock(&mutex);
}
}

