【发布时间】:2017-06-20 04:16:16
【问题描述】:
我使用multi-threading 编写了一个代码,它创建了两个threads。
-
Consumer Thread:到dequeue来自Circular Queue的一个元素。 -
Producer Thread:转至enqueueCircular Queue中的十个元素。
Consumer Thread 在插入六个元素之前处于等待状态,并且仅在 Producer Thread 在 queue 中插入六个元素之后才有效,即 dequeue 元素。以下是我的代码:
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
}
代码在Windows(CodeBlocks) 中按预期工作。
- 0-5 先插入队列
- 在插入 6 时,达到阈值并从
queue中删除一个元素。 - 在此之后,
queue中插入了 6-9。
但是在Ubuntu 中执行时,首先插入0-9 个元素,然后从queue 中删除一个元素。
用于在ubuntu 中编译的命令:g++ -pthread name.cpp。
这种不同行为的原因是什么以及如何解决这个问题?
完整代码Follow link
【问题讨论】:
-
这里的代码太多了。这可以简化为minimal reproducible example
-
我已经添加了整个程序,以便检查整个功能。它是一个没有错误的程序。虽然主要功能仅在
Producer和Consumer函数中实现,但由于问题在 ubuntu 中执行,我添加了整个代码,以便可以在 ubuntu 中检查和执行它。现在,为了您的方便,我删除了额外的代码。 -
现在它不是一个工作示例...您必须再次添加一些或代码,以便我们可以重现问题
-
@koleygr 我添加了整个代码的链接Here。在你自己的 IDE 中试试这个。
-
恕我直言,这是 C.
标签: c multithreading ubuntu