这篇文章介绍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.