一.buffer.h的声明,如下:
#ifndef BUFFER_H
#define BUFFER_H
#include <iostream>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <stack>
class buffer{
public:
buffer(size_t n):unRead(0),capacity(n){}
void put(int x);
void get(int* x);
private:
bool is_full();
bool is_empty();
private:
boost::mutex mu;
boost::condition_variable_any putCond;
boost::condition_variable_any getCond;
std::stack<int> stk;
int unRead;
int capacity;
};
inline bool buffer::is_full(){
return unRead == capacity;
}
inline bool buffer::is_empty(){
return unRead == 0;
}
#endif
转正请注明出处:山水间博客:http://blog.csdn.net/linyanwen99/article/details/8227020
二.buffer.cpp的实现,如下:
#include "buffer.h"
boost::mutex io_mu;
void buffer::put(int x)
{
{
boost::mutex::scoped_lock lock(mu);
while(is_full())
{
{
boost::mutex::scoped_lock lock(io_mu);//io流是共享资源,不是线程安全的,故需要锁定,以下同理。
std::cout<<"stack is full,please wait..."<<std::endl;
}
putCond.wait(mu);
}
stk.push(x);
++unRead;
}
getCond.notify_one();
}
void buffer::get(int* x)
{
{
boost::mutex::scoped_lock lock(mu);
while(is_empty())
{
{
boost::mutex::scoped_lock lock(io_mu);
std::cout<<"stack is empty,please wait..."<<std::endl;
}
getCond.wait(mu);
}
--unRead;
*x = stk.top();
stk.pop();
}
putCond.notify_one();
}
转正请注明出处:山水间博客:http://blog.csdn.net/linyanwen99/article/details/8227020
三.main.cpp的实现,如下:
#include <boost/thread/thread.hpp>
#include <string>
#include "buffer.h"
extern boost::mutex io_mu;
buffer buf(5);
void producer(int n,std::string str,int seq)
{
for(int i=0;i<n;++i)
{
{
boost::mutex::scoped_lock lock(io_mu);
std::cout<<"["<<str<<"->"<<seq<<"]"<<" put data "<<i<<std::endl;
}
buf.put(i);
sleep(1);
}
}
void consumer(int n,std::string str,int seq)
{
int x;
for(int i=0;i<n;++i)
{
buf.get(&x);
boost::mutex::scoped_lock lock(io_mu);
std::cout<<"["<<str<<"->"<<seq<<"]"<<" get data "<<x<<std::endl;
sleep(1);
}
}
int main(int argc,char** argv)
{
boost::thread t1(producer,10,"producer",1);
boost::thread t2(consumer,5,"consumer",1);
boost::thread t3(consumer,5,"consumer",2);
t1.join();
t2.join();
t3.join();
return 0;
}
说明:代码简洁明了,无需赘述。
四.可能会出现的问题,如下:
undefined reference to `boost::thread_resource_error::thread_resource_error()'
说明:该问题其实很好解决,当然也得看具体情况,这里略去。
五.makefile的编写请参考前一篇
参考文献:boost库完全开发指南,罗剑锋 著
转正请注明出处:山水间博客:http://blog.csdn.net/linyanwen99/article/details/8227020