[英]Synchronizing two pthreads using mutex in C
在使用互斥量同步两个线程时需要帮助。 我是C和互斥锁的新手,我不确定在这里做什么。 该代码有两个线程,总数为10,并打印出每个数字,但不同步,因此不会同步打印,而是同步一半。 意味着我最终只会遇到麻烦,有时会打印8..9..11、8..9..10..10等。
如果您删除了关于互斥锁的代码,那我就无法更改原始代码。 我只能添加关于互斥锁的行。
#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;
}
在互斥锁之外的情况下,您可能收不到正确的值。 确保循环按顺序运行的保证方法是对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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.