boost::mutex的最简单的例子

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <iostream>
//使用boost::mutex的最简单的例子。
//例子中共创建了两个新的线程,每个线程都有10次循环,在std::cout上打印出线程id和当前循环的次数,
//而main函数等待这两个线程执行完才结束。std::cout就是共享资源,所以每一个线程都使用一个全局互斥体来保证同时只有一个线程能向它写入
boost::mutex io_mutex;

struct count
{
	count(int id) : id(id) { }

	void operator()()
	{
		for (int i = 0; i < 10; ++i)
		{
			boost::mutex::scoped_lock
				lock(io_mutex);
			std::cout << id << ": "
				<< i << std::endl;
		}
	}

	int id;
};

int main(int argc, char* argv[])
{
	boost::thread thrd1(count(1));
	boost::thread thrd2(count(2));
	thrd1.join();
	thrd2.join();
	return 0;
}
/*
1: 0
1: 1
1: 2
1: 3
1: 4
1: 5
1: 6
1: 7
1: 8
1: 9
2: 0
2: 1
2: 2
2: 3
2: 4
2: 5
2: 6
2: 7
2: 8
2: 9
请按任意键继续. . .
*/


#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
#include <iostream>
//使用Boost.Bind来简化创建线程携带数据,避免使用函数对象
boost::mutex io_mutex;

void count(int id)
{
	for (int i = 0; i < 10; ++i)
	{
		boost::mutex::scoped_lock
			lock(io_mutex);
		std::cout << id << ": " <<
			i << std::endl;
	}
}

int main(int argc, char* argv[])
{
	//boost::bind  对自由方法来说,直接boost::bind(函数名, 参数1,参数2,...)
	boost::thread thrd1(boost::bind(&count, 1));
	boost::thread thrd2(boost::bind(&count, 2));
	thrd1.join();
	thrd2.join();
	return 0;
}
/*
2: 0
2: 1
2: 2
2: 3
2: 4
2: 5
2: 6
2: 7
2: 8
2: 9
1: 0
1: 1
1: 2
1: 3
1: 4
1: 5
1: 6
1: 7
1: 8
1: 9
请按任意键继续. . .
*/


你可能感兴趣的:(boost::mutex的最简单的例子)