现在的位置: 首页 > 综合 > 正文

boost 使用(四)

2013年09月29日 ⁄ 综合 ⁄ 共 582字 ⁄ 字号 评论关闭

使用boost中的线程库中的锁,先介绍简单的锁的用方法,会api锁的人可以跳过了,和api的没有区别的,新手请继续。先贴上代码:

#include <boost/thread.hpp> 
#include <iostream> 

void wait(int seconds)
{
	boost::this_thread::sleep(boost::posix_time::seconds(seconds));
}

boost::mutex mutex;

void thread()
{
	for (int i = 0; i < 5; ++i)
	{
		wait(1);
		mutex.lock();
		std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl;
		mutex.unlock();
	}
}

int main()
{

	boost::thread t1(thread);
	boost::thread t2(thread);
	t1.join();
	t2.join();
	system("pause");
}

好了附上运行结果吧:

你会发现没有太多新加的内容,只有mutex.lock和 mutex.unlock;这两个新的函数,这个是加锁和解锁两个操作。好了这就是这次带来的内容。这个操作可以保证多线程中改变同样的地址空间的时候不会发生悲剧。保证线程安全。好了学过操作系统的你一定懂。

抱歉!评论已关闭.