使用 sleep() 时,生产者使用者(使用监视器)代码不起作用
producer consumer (using Monitor) code is not working when sleep() is used?
#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]
你尝试运行该程序多久了?
您是否阅读了兰德和睡眠的文档。
兰特函数链接
睡眠功能链接
兰德每次都可能返回一个大数字,而您的生产者在第一次生产东西后会睡很长时间,在此期间,您的消费者只是等待cond_wait。
尝试使用较小的睡眠间隔"usleep"或类似的东西,您会发现您的程序运行良好。
毫/微秒休眠功能链路
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 用于C++代码的 API 监视器类型定义 (XML)
- C++端口监视器 (mfilemon.dll) RDP 虚拟通道代码未执行
- 串行监视器不显示安装程序或主控制器中的代码 - 波特率9600
- 使用 sleep() 时,生产者使用者(使用监视器)代码不起作用