gpt4 book ai didi

c - 在 C 中使用互斥锁同步两个 pthread

转载 作者:太空宇宙 更新时间:2023-11-04 03:57:46 25 4
gpt4 key购买 nike

需要有关使用互斥体同步两个线程的帮助。我是 C 语言和互斥体的新手,我不确定在这里做什么。该代码有两个线程数到十并打印出每个数字,但不是同步的,因此它不会同步打印,它是半同步的。意味着我最后只会遇到麻烦,有时它会打印 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);
}
}

关于c - 在 C 中使用互斥锁同步两个 pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840135/

25 4 0