boost::condition_variable的使用

6 篇文章 0 订阅

这篇文章介绍boost::condition_variable的使用。

主要是在多线程的情况下,一般来说boost::condition_variable是用来进行多线程同步的,下面的代码主要测试了notify_one和notify_all的使用。

调用notify_one的时候,启用一个线程。

调用notify_all的时候,激活所有的线程。

当频繁调用notify_one的时候,并不会一直调用唯一的一个线程(在多个线程的情况下),他会激活其他线程,所以优先使用notify_one。

当数据量小于线程数量的时候,如果调用notify_all则会造成其他线程的空运行。

在结尾,附上测试结果。



// ThreadTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include "boost/thread.hpp"
#include "boost/thread/condition_variable.hpp"
#include "boost/thread/mutex.hpp"
#include <thread>
#include <iostream>
#include <windows.h>

boost::condition_variable _g_cv;
boost::mutex _g_cv_mutex;
bool _g_is_quit = false;


void ThreadFunc_1()
{
	boost::mutex::scoped_lock lock(_g_cv_mutex);

	while (!_g_is_quit)
	{
		_g_cv.wait(lock);
		printf("ThreadFunc_1.\n");
		// Sleep(10);
	}
}

void ThreadFunc_2()
{
	boost::mutex::scoped_lock lock(_g_cv_mutex);

	while (!_g_is_quit)
	{
		_g_cv.wait(lock);
		printf("ThreadFunc_2.\n");
		// Sleep(10);
	}
}

void ThreadFunc_3()
{
	boost::mutex::scoped_lock lock(_g_cv_mutex);

	while (!_g_is_quit)
	{
		_g_cv.wait(lock);
		printf("ThreadFunc_3.\n");
		// Sleep(10);
	}
}

void ThreadFunc_4()
{
	boost::mutex::scoped_lock lock(_g_cv_mutex);

	while (!_g_is_quit)
	{
		_g_cv.wait(lock);
		printf("ThreadFunc_4.\n");
		// Sleep(10);
	}
}


void ThreadControl()
{
#define THREADCOUNT	4

	typedef void(*FUNC)();
	FUNC threadArray[4] = { ThreadFunc_1, ThreadFunc_2, ThreadFunc_3, ThreadFunc_4 };

	for (size_t i = 0; i < THREADCOUNT; i++)
	{
		boost::thread th(threadArray[i]);
	}
}


int _tmain(int argc, _TCHAR* argv[])
{
	ThreadControl();

	using namespace std;
	int value = 0;
	while (true)
	{
		printf("enter 1 to notify one thread.\n");
		printf("enter 2 to notify thread one by one.\n");
		printf("enter 3 to notify all threads.\n");
		printf("enter <-1> to quit.\n");

		cin >> value;
		switch (value)
		{
		case -1:
			_g_is_quit = true;
			break;
		case 1:
			_g_cv.notify_one();
			break;
		case 2:
			for (size_t i = 0; i < THREADCOUNT; i++)
			{
				_g_cv.notify_one();
			}
			break;
		case 3:
			_g_cv.notify_all();
			break;
		default:
			printf("enter again.\n");
			break;
		}

		if (_g_is_quit){
			break;
		}
	}

	system("pause");
	return 0;
}


测试结果:

--------------------------------
enter 1 to notify one thread.
enter 2 to notify thread one by one.
enter 3 to notify all threads.
enter <-1> to quit.
1
ThreadFunc_3.


2
ThreadFunc_2.
ThreadFunc_1.
ThreadFunc_4.
ThreadFunc_3.




4
enter again.


3
ThreadFunc_2.
ThreadFunc_1.
ThreadFunc_3.
ThreadFunc_4.

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值