Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C语言中增加多线程结构的值_C_Multithreading_Queue - Fatal编程技术网

如何在C语言中增加多线程结构的值

如何在C语言中增加多线程结构的值,c,multithreading,queue,C,Multithreading,Queue,我想增加存储在结构中的计数器的值。3根线进入fonction纹身店以增加人数,但由于某些原因,人数的价值保持不变 我试着按顺序复制这个案子,结果成功了。当我使用线程时,有什么特别的事情要做吗?谢谢:) 输出: 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

我想增加存储在结构中的计数器的值。3根线进入fonction纹身店以增加人数,但由于某些原因,人数的价值保持不变

我试着按顺序复制这个案子,结果成功了。当我使用线程时,有什么特别的事情要做吗?谢谢:)

输出:

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

您的代码是无意义的,因为
将_队列排队是局部变量,而不是共享变量

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

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

    printf("%d", people);
}

_队列是一个局部变量,每次调用例程时,我不清楚你的多个线程是如何共享同一个队列的。@OliverCharlesworth我的线程都将进入函数纹身商店,然后进入函数添加到队列中。因此每个线程都创建自己的队列。
静态队列应该有助于多个队列显示我可以使_队列共享吗?问题是,我需要从函数中获取这些数据,然后将_添加到_队列中,以便在纹身商店中执行测试。@MaxUt:在函数之外定义队列(文件静态变量)。这也将其初始化为零;您的代码增加了一个未初始化的变量,您很幸运,内存恰好为零(可能是为了防止您窥探前一个进程存储在同一物理内存中的数据,但任何标准都不能保证这一点)。并且对队列的所有访问都需要由互斥体进行调解(我注意到,互斥体在所示代码中没有定义/声明,但必须是一个文件范围变量)。您的打印代码应该在互斥锁/解锁对的范围内。
{
    pthread_mutex_lock(&mutex_queue);
    int people = the_queue->number_of_people++;
    pthread_mutex_unlock(&mutex_queue);

    printf("%d", people);
}