gpt4 book ai didi

c - 如何在C中增加具有多线程的结构的值

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

我想增加存储在结构中的计数器的值。 3 个线程进入函数 tattoo_shop 以增加人数,但由于某些原因,number_of_people 的值保持不变。

我尝试按顺序重现该案例并且它正在运行。当我使用线程时有什么特别的事情要做吗?谢谢:)

typedef struct {
int number_of_people;
}Queue;

void *tattoo_shop(void *arguments){
Client *args = arguments;
Queue the_queue;

add_to_the_queue(&the_queue,args);
}

void add_to_the_queue(Queue *the_queue, Client *the_client) {

pthread_mutex_lock(&mutex_queue);
the_queue->number_of_people++;
pthread_mutex_unlock(&mutex_queue);

printf("The thread %d is changing the counter of the queue which is now %d \n",the_client->id,the_queue->number_of_people);
}

输出:

The thread 1 is changing the counter of the queue which is now 1 
The thread 0 is changing the counter of the queue which is now 1
The thread 2 is changing the counter of the queue which is now 1

最佳答案

您的代码是无意义的,因为 Queue the_queue; 是一个局部变量,而不是共享变量。

但是如果它是在文件范围内分配的,或者作为 static,代码基本上没问题。迂腐地,你不应该在互斥保护之外读取共享对象,因为从其他地方写入对象不能保证是原子的。稍作调整以解决此问题:

{
pthread_mutex_lock(&mutex_queue);
int people = the_queue->number_of_people++;
pthread_mutex_unlock(&mutex_queue);

printf("%d", people);
}

关于c - 如何在C中增加具有多线程的结构的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47926373/

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