#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
答案 0 :(得分:3)
当我使用fflush(stdout)
时,我看到输出正在打印while(true){
cout<<"["<<b.consume()<<"] ";
fflush(stdout)
}
<强>输出:强>
Magnum @ SimpleGuy:〜[52] $ ./a.out [1] [2] [3] [4] [5] [6] [7] [8]
答案 1 :(得分:-1)
您尝试运行该程序多久了?
您是否阅读了兰德和睡眠的文档?
Rand function Link
兰德每次都会返回一个大数字并且你的制作人在第一次制作东西后长时间睡觉会发生这种情况,并且在这段时间你的消费者只需要等待cond_wait。
尝试使用较小的睡眠间隔&#39; usleep&#39;或类似的东西,你会发现你的程序工作正常。