【发布时间】:2017-12-21 13:50:30
【问题描述】:
我想增加存储在结构中的计数器的值。 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
【问题讨论】:
-
the_queue 是一个局部变量,每次调用例程都会重新初始化
-
我不清楚您的多个线程如何最终共享同一个队列。
-
@OliverCharlesworth 我的线程都进入函数纹身店,然后它们进入函数 add_to_the_queue。
-
所以每个人都会创建自己的队列。
-
static Queue the_queue;应该有助于处理多个队列
标签: c multithreading queue