该例子的功能是:
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;
}