参考链接:http://stlchina.huhoo.net/twiki/bin/view.pl/Main/BoostThread
/*
@description 读者写者问题的实现
1.使用scoped_lock对成员变量Mutex加锁,实现对象的互斥访问(也就是缓冲数组的互斥访问)
2.使用scoped_lock对std::cout互斥访问
3.当A线程等待时,应该对mutex解锁,以使B线程能够访问缓冲区,然后唤醒A,因此使用con.wait(slock);
来阻塞当前线程并解开缓冲锁
**/
#include <iostream>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/thread.hpp>
using namespace std;
const int BUFFER_SIZE = 10;
const int SEND_CNT = 100;
boost::mutex io_mutex;
class buffer{
public:
buffer():p(0),g(0),full(0){}
void put(int n){
boost::mutex::scoped_lock slock(mutex);
if(full == BUFFER_SIZE){
{
boost::mutex::scoped_lock lock(io_mutex);
cout<<"buffer is full.waiting..."<<endl;
}
while(full == BUFFER_SIZE)
con.wait(slock);
}
buf[p] = n;
p = (p + 1) % BUFFER_SIZE;
full++;
con.notify_one();
}
int get(){
boost::mutex::scoped_lock slock(mutex);
if(full == 0){
{
boost::mutex::scoped_lock slock(io_mutex);
cout<<"buffer is empty.waiting..."<<endl;
}
while(full == 0)
con.wait(slock);
}
int x = buf[g];
g = (g + 1) % BUFFER_SIZE;
full--;
con.notify_one();
return x;
}
private:
int full;
boost::condition con;
boost::mutex mutex;
int buf[SEND_CNT];
int p,g;
};
buffer buff;
void writer(){
for(int i = 0;i < SEND_CNT;++i){
{
boost::mutex::scoped_lock lock(io_mutex);
cout<<"sending :"<<i<<endl;
}
buff.put(i);
}
}
void reader(){
for(int i = 0;i < SEND_CNT;i++){
int x = buff.get();
{
boost::mutex::scoped_lock lock(io_mutex);
cout<<"reading :"<<x<<endl;
}
}
}
int main(int argc,char* argv[])
{
boost::thread thr1(boost::bind(&writer));
boost::thread thr2(boost::bind(&reader));
thr1.join();
thr2.join();
system("pause");
return 0;
}
初学boost,错误之处,敬请指正,感激不尽。