如何提供交织线程以表明一个code场所及不提供完美的同步序列? [英] How to provide a sequence of interleaving threads to show that a code breaks and doesn't provide perfect synchronization?

查看:115
本文介绍了如何提供交织线程以表明一个code场所及不提供完美的同步序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道下面code做什么,我知道为什么它是一个破碎的code同步,因为它只有一个条件变量,而我们需要两个,但我不知道如何提供的序列为显示这是行不通的交织线程。你能说明为什么code没有用一个例子来工作?

  1 cond_t COND = PTHREAD_COND_INITIALIZER;
2为mutex_t互斥= PTHREAD_MUTEX_INITIALIZER ;;
3
4无效*制片人(无效* ARG){
5 INT I;
6(I = 0; I<循环;我++){
7调用pthread_mutex_consistent_np(安培;互斥);
8时(计数== 1)
9调用pthread_cond_wait(安培; COND,和放大器;互斥);
10将(I)
11调用pthread_cond_signal(安培; COND);
12调用pthread_mutex_unlock(安培;互斥);
13}
14}
15
16 void *的消费者(无效* ARG){
17 INT I;
18(I = 0; I<循环;我++){
19调用pthread_mutex_consistent_np(安培;互斥);
20时(计数== 0)
21调用pthread_cond_wait(安培; COND,和放大器;互斥);
22 INT TMP = get()方法;
23调用pthread_cond_signal(安培; COND);
24调用pthread_mutex_unlock(安培;互斥);
25的printf(%d个\\ N,TMP);
26}
27}


解决方案

presuming的把()计数 1和的get()计数 0,此code实际上是精细的只要你只有一个生产者和一个消费者

如果你有一个以上的生产商,那么调用pthread_cond_signal()在生产者可能唤醒了其他生产者而不是消费者之一,那么没有消费者会继续。存在同样的问题,如果你有一个以上的消费。

您可以通过引入独立的条件变量为空和满的,或使用调用pthread_cond_broadcast解决这个问题()而不是调用pthread_cond_signal()

I know what the following code does and I know why it is a broken code for synchronization as it has only one conditional variable while we need two but I don't know how to provide a sequence of interleaving threads for showing it doesn't work. Can you show why this code doesn't work with an example?

1   cond_t cond = PTHREAD_COND_INITIALIZER; 
2  mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;;
3
4  void *producer(void *arg) {
5    int i;
6    for (i = 0; i < loops; i++) {
7      Pthread_mutex_lock(&mutex);
8      while (count == 1)
9        Pthread_cond_wait(&cond, &mutex);
10     put(i);
11     Pthread_cond_signal(&cond);
12     Pthread_mutex_unlock(&mutex);
13   }
14 }
15
16 void *consumer(void *arg) {
17   int i;
18   for (i = 0; i < loops; i++) {
19     Pthread_mutex_lock(&mutex);
20     while (count == 0)
21       Pthread_cond_wait(&cond, &mutex);
22     int tmp = get();
23     Pthread_cond_signal(&cond);
24     Pthread_mutex_unlock(&mutex);
25     printf("%d\n", tmp);
26   }
27 }

解决方案

Presuming that put() sets count to 1 and get() sets count to 0, this code is actually fine as long as you have only one producer and one consumer.

If you have more than one producer, then the pthread_cond_signal() in the producer might wake up one of the other producers instead of a consumer, and then no consumers will proceed. The same problem exists if you have more than one consumer.

You can fix this either by introducing separate condition variables for empty and full, or by using pthread_cond_broadcast() instead of pthread_cond_signal().

这篇关于如何提供交织线程以表明一个code场所及不提供完美的同步序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆