該例子的功能是:
1、創建測試線程
2、創建工作線程
3、使用list隊列
4、線程通知
5、線程鎖
工作線程如果沒有活要做,則掛起,如果消息隊列裏有新的消息了,則通知工作線程開始幹活。說多了都是廢話,上代碼:
// ConsoleApplication3.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include "boost/thread.hpp"
#include "boost/thread/condition_variable.hpp"
#include "boost/thread/mutex.hpp"
#include "boost/shared_ptr.hpp"
#include "boost/function.hpp"
#include "boost/bind.hpp"
#include <list>
#include <iostream>
boost::shared_ptr<std::list<int>> _g_list;
boost::mutex _g_mutex_lock_list;
boost::condition_variable _g_cv;
boost::mutex _g_cv_mutex;
/*
* \brief
* t:
* f: no quit
*/
bool _g_is_quit = false;
void Add(int value)
{
{
boost::mutex::scoped_lock lock(_g_mutex_lock_list);
if (_g_list){
_g_list->push_front(value);
}
}
_g_cv.notify_one();
}
void CreateThr(int threadCnt)
{
if (!threadCnt)
{
// no thread
return;
}
// thread function
boost::function<void(void)> func = []()
{
int cnt = 10;
while (--cnt)
{
Add(cnt);
}
};
for (size_t i = 0; i < (size_t)threadCnt; ++i)
{
boost::thread th(boost::bind(func));
//boost::thread th(func);
}
}
int GetValueFromList()
{
boost::mutex::scoped_lock lock(_g_mutex_lock_list);
if (!_g_list->size()){
return 0;
}
int v = _g_list->back();
_g_list->pop_back();
return v;
}
// first launch work thread
void WorkThread()
{
#define WORKTHREADCNT 1
auto func = []()
{
int value = 0;
int cnt = 0;
boost::mutex::scoped_lock lock(_g_cv_mutex);
while (!_g_is_quit)
{
value = GetValueFromList();
if (!value){
_g_cv.wait(lock);
continue;
}
printf("%3d,", value);
++cnt;
if (cnt != 0 && cnt % 9 == 0){
printf("\n");
}
}
};
for (size_t i = 0; i < WORKTHREADCNT; i++)
{
boost::thread th(func);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
_g_list = boost::shared_ptr<std::list<int>>(new std::list<int>());
WorkThread();
CreateThr(4);
int value = 0;
while (value != -1)
{
if (value == -1){
_g_is_quit = true;
_g_cv.notify_all();
break;
}
using namespace std;
cout << "enter a number, enter [-1] to quit.\n";
cin >> value;
Add(value);
}
system("pause");
return 0;
}