gpt4 book ai didi

c - 线程与互斥体同步

转载 作者:行者123 更新时间:2023-11-30 17:32:51 25 4
gpt4 key购买 nike

我有两个线程。第一个应该写:

1
2
3
4
5
6
7
8
9

第二个应该写:

am 1
am 2
am 3
am 4
am 5
am 6
am 7
am 8
am 9

这是我的代码:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

pthread_mutex_t mutex;

int firstCounter = 0;
int secondCounter = 0;

void *writeloop(void *arg) {
while(firstCounter < 10) {
pthread_mutex_lock(&mutex);
firstCounter++;
printf("%d\n", firstCounter);
pthread_mutex_unlock(&mutex);
}
exit(0);
}

void *readLoop(void *arg) {
while(secondCounter < 10) {
pthread_mutex_lock(&mutex);
secondCounter++;
printf("am %d\n", secondCounter);
pthread_mutex_unlock(&mutex);
}
exit(0);
}

int main(void)
{
pthread_t tid, fid;
pthread_mutex_init(&mutex, NULL);
pthread_create(&tid, NULL, writeloop, NULL);
pthread_create(&fid, NULL, readLoop, NULL);
pthread_join(tid, NULL);
pthread_join(fid, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}

但它无法正常工作。有时第二种方法不起作用,有时却有效。有时第一个工作正常,有时会打印:

1
2
3
4
5
6
7

我的错误在哪里?

最佳答案

最好使用两个不同的互斥变量来处理两个线程的读写操作。

因为在当前情况下,它完全取决于调度,如果写线程首先获得调度,那么它会获取互斥锁。因此,稍后的读取线程必须等待互斥锁,直到写入线程释放它,反之亦然。

关于c - 线程与互斥体同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23983324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com