boost综合使用<function,bind,thread,mutex,condition_variable,shared_ptr>

该例子的功能是:

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值