多个线程在C

时间:2017-06-20 04:16:16

标签: c multithreading ubuntu

我使用multi-threading编写了代码,创建了两个threads

  • Consumer Thread:来自dequeue的{​​{1}}个元素。
  • Circular QueueProducer Thread中的enqueue十个元素。

Circular Queue在插入六个元素之前处于等待状态,仅在Consumer Thread dequeue中插入六个元素后才起作用Producer Thread元素。以下是我的代码:< / p>

queue

代码在void *producer(void *t) { int i; long my_id = (long)t; for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); printf("\nInserting value = %d ",count); enQueue(count); displayQueue(); count++; if (count == 6) { pthread_cond_signal(&count_threshold_cv); printf("\nproducer: thread %ld, count = %d Threshold reached.\n",my_id, count); } printf("\nproducer: thread %ld, count = %d, unlocking mutex\n",my_id, count); pthread_mutex_unlock(&count_mutex); } pthread_exit(NULL); } void *consumer(void *t) { long my_id = (long)t; printf("Starting Consumer Thread(): thread %ld\n", my_id); pthread_mutex_lock(&count_mutex); while (count<6) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("\nconsumer: thread %ld Condition signal received.\n", my_id); } printf(" \nDeleted value =%d ",deQueue()); displayQueue(); printf("\nconsumer: thread %ld count now = %d.\n", my_id, count); pthread_mutex_unlock(&count_mutex); pthread_exit(NULL); } int main (int argc, char *argv[]) { int i, rc; long t1=1, t2=2; pthread_t threads[2]; //Threads Created pthread_create(&threads[1], &attr, consumer, (void *)t1); pthread_create(&threads[0], &attr, producer, (void *)t2); //Thread Clean Up Followed } 中按预期工作。

  • 0-5首先插入队列
  • 在插入6时,达到了阈值,并从Windows(CodeBlocks)中删除了一个元素。
  • 此后,6-9插入queue

但是当在queue中执行时,会插入First 0-9元素,然后从Ubuntu中删除一个元素。 用于在queue中编译的命令:ubuntu。 这种不同行为的原因是什么以及如何解决这个问题? 对于整个代码Follow link

2 个答案:

答案 0 :(得分:0)

  

这种不同行为的原因是什么

线程不会保证两个不同线程中的内容将以任何特定顺序发生,除非您明确同步以便它们执行。你没有同步,所以事情按某种顺序发生,然后它们以不同的顺序发生。这完全是预期的。

如果您希望事情以某种顺序发生,您必须明确地让两个线程彼此等待或不使用线程。

由于你的代码现在没有任何东西阻止“生产者”循环10次然后退出。

答案 1 :(得分:-1)

有些情况会在代码中创建死锁。作为一个例子,如果消费者&#39;线程在“生产者”之前开始。线程它创建死锁情况。消费者&#39;等待发出信号&#39; count_threshold_cv&#39;它已经获得了&#39; count_mutex&#39;互斥。制片人的平均时间&#39;正在等待获得&#39; count_mutex&#39;。因此,此死锁情况会导致应用程序挂起。请设计申请以避免这种情况。我们无法保证哪个线程首先启动。特别是获取互斥锁应仅适用于所需的代码段集。

编辑:因为&#39; pthread_cond_wait&#39;传递&#39; count_mutex&#39;这不会造成死锁。但由于我们无法保证线程执行的顺序,因此行为是不可预测的。 此外,你不能依靠cout out put。由于输出可能不是受让人的执行顺序。

相关问题