可通过设置操作系统的管道容量参数,另外由于read和write函数阻塞,故可以通过管道实现阻塞队列,且相比使用condition来说,可以避免signal先于wait到达的情况下造成的长时间不必要的等待
/*
* Pipe.cpp
*
* Created on: 2014年6月10日
* Author:
*/
#include <iostream>
#include <pthread.h>
using namespace std;
int d[2];
void * take(void *)
{
char buffer[100];
read(d[0],buffer,100);
cout << "get data "<< buffer <<endl;
return NULL;
}
void * put(void *)
{
write(d[1],"hello pipe!",20);
cout << "write data " <<endl;
return NULL;
}
int main()
{
void* ret;
pthread_t customer,producer;
pipe(d);
pthread_create(&customer, NULL, take, NULL);
sleep(2);
pthread_create(&producer, NULL, put, NULL);
pthread_join(customer, &ret);
pthread_join(producer, &ret);
return 0;
}
本文介绍了一种通过设置操作系统的管道容量参数来实现阻塞队列的方法,并通过一个简单的C++示例展示了如何使用管道进行进程间通信。该方法能够有效避免使用condition变量时可能出现的信号提前到达问题。
1320

被折叠的 条评论
为什么被折叠?



