gpt4 book ai didi

c++ - 使用 sleep() 时生产者消费者(使用 Monitor)代码不工作?

转载 作者:行者123 更新时间:2023-11-30 03:59:06 26 4
gpt4 key购买 nike

#include<bits/stdc++.h>
#include<pthread.h>
#include<unistd.h>
#define MAX 10
using namespace std;
class BoundedBuffer
{
private:
int buffer[MAX];
int fill, use;
int fullEntries;
pthread_mutex_t monitor; // monitor lock
pthread_cond_t empty;
pthread_cond_t full;
public:
BoundedBuffer ()
{
use = fill = fullEntries = 0;
}
void produce (int element)
{
pthread_mutex_lock (&monitor);
while (fullEntries == MAX)
pthread_cond_wait (&empty, &monitor);
buffer[fill] = element;
fill = (fill + 1) % MAX;
fullEntries++;
//sleep(rand()%2);
pthread_cond_signal (&full);
pthread_mutex_unlock (&monitor);
}
int consume ()
{
pthread_mutex_lock (&monitor);
while (fullEntries == 0)
pthread_cond_wait (&full, &monitor);
int tmp = buffer[use];
use = (use + 1) % MAX;
fullEntries--;
//sleep(rand()%2);
pthread_cond_signal (&empty);
pthread_mutex_unlock (&monitor);
return tmp;
}
}b;
void* producer(void *arg){
int i=1;
while(true){
b.produce(i);
i++;
}
}
void* consumer(void *arg){
while(true){
cout<<b.consume()<<" ";
}
}
int main(){
pthread_t t1,t2;
pthread_create(&t1,NULL,producer,NULL);
pthread_create(&t2,NULL,consumer,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
return 0;
}

每当在 BoundedBuffer.consume() 和 BoundedBuffer.produce(int ) 中添加 sleep() 时,它不会打印任何输出。但是当这些函数中没有 sleep() 时,它可以正常工作并将输出打印为应该是。为什么会这样?
引用: http://pages.cs.wisc.edu/~remzi/OSTEP/threads-monitors.pdf

最佳答案

当我使用 fflush(stdout) 时,我看到正在打印输出

while(true){
cout<<"["<<b.consume()<<"] ";
fflush(stdout)
}

输出:

Magnum@SimpleGuy:~ [52]$ ./a.out [1] [2] [3] [4] [5] [6] [7] [8]

关于c++ - 使用 sleep() 时生产者消费者(使用 Monitor)代码不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27099185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com