版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pzhw520hchy/article/details/81837625
mydata.h
#ifndef _MYDATA_H_
#define _MYDATA_H_
#endif
#include "stdafx.h"
#include<iostream>
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define MAX_SIZE 100
class resdata
{
public:
resdata();
resdata(const int iqueue_size);
~resdata();
public:
int get();
void put(int i);
bool isempty();
bool isfull();
bool isStop();
void SetStop(bool);
private:
std::queue<int> m_data_queue;
int m_queue_max_size;
boost::mutex io_mutex;
boost::mutex data_mutex;
boost::mutex stop_mutex;
boost::condition_variable queue_not_full, queue_not_empty;
bool m_bstop;
};
mydata.cpp
#include "stdafx.h"
#include "mydata.h"
resdata::resdata()
{
}
resdata::resdata(const int n) :m_queue_max_size(n), m_bstop(false)
{
}
resdata::~resdata()
{
}
int resdata::get()
{
while (isempty() && !isStop())
{
boost::mutex::scoped_lock lk(data_mutex);
queue_not_empty.wait(lk);
}
int i = m_data_queue.front();
m_data_queue.pop();
queue_not_full.notify_one();
return i;
}
void resdata::put(int i)
{
while (isfull() && !!isStop())
{
boost::mutex::scoped_lock lk(data_mutex);
queue_not_full.wait(lk);
}
m_data_queue.push(i);
queue_not_empty.notify_one();
}
bool resdata::isempty()
{
boost::mutex::scoped_lock lk(data_mutex);
return m_data_queue.empty();
}
bool resdata::isfull()
{
boost::mutex::scoped_lock lk(data_mutex);
return (m_queue_max_size == m_data_queue.size());
}
bool resdata::isStop()
{
boost::mutex::scoped_lock lk(stop_mutex);
return m_bstop;
}
void resdata::SetStop(bool bstop)
{
boost::mutex::scoped_lock lk(stop_mutex);
m_bstop = bstop;
}
main.cpp
// boost_thread_t.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "mydata.h"
resdata *dataqueue = new resdata(3);
boost::mutex io_mutex;
void productor(int no) {
int n = 0;
while (n < 100) {
dataqueue->put(n);
boost::mutex::scoped_lock lkio(io_mutex);
std::cout << no << "sent: " << n << std::endl;
++n;
}
dataqueue->put(-1);
dataqueue->SetStop(true);
}
void consumer(int no) {
int n;
do {
n = dataqueue->get();
boost::mutex::scoped_lock lkio(io_mutex);
std::cout << no << "received: " << n << std::endl;
} while (n != -1 && !dataqueue->isStop()); // -1 indicates end of buffer
dataqueue->SetStop(true);
}
int _tmain(int argc, _TCHAR* argv[])
{
boost::thread thrd1(&productor, 1);
boost::thread thrd2(&consumer, 1);
boost::thread thrd3(&consumer, 2);
thrd1.join();
thrd2.join();
thrd3.join();
return 0;
}