【问题标题】:How to increment the value of a structure with multiple thread in C如何在C中增加具有多个线程的结构的值
【发布时间】: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


【解决方案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);
}

【讨论】:

  • 如何使 the_queue 共享?问题是我需要从函数 add_to_the_queue 中获取这些数据,以便在纹身店中执行测试。
  • @MaxUt:您在函数之外定义队列(文件静态变量)。这也将其初始化为零;您的代码增加了一个未初始化的变量,并且您很幸运内存恰好被归零(可能是为了防止您窥探前一个进程存储在同一物理内存中的数据,但任何标准都不能保证这一点)。并且所有对队列的访问都需要由互斥体进行调解(我注意到,在显示的代码中没有定义/声明,但必须是文件范围变量)。您的打印代码应该在互斥锁/解锁对的范围内。
猜你喜欢
  • 2021-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-30
相关资源
最近更新 更多