C++ boost thread学习(二)

线程中断

在一个线程对象上调用 interrupt() 会中断相应的线程,并会在这个线程中抛出一个类型为 boost::thread_interrupted 的异常。

如果给定的线程不包含任何中断点,简单调用interrupt就不会起作用。 每当一个线程中断点,它就会检查interrupt是否被调用过。只有被调用过了, boost::thread_interrupted 异常才会相应地抛出。

Boost.Thread定义了一系列的中断点,例如sleep() 函数,由于sleep() 在这个例子里被调用了五次,该线程就检查了五次它是否应该被中断。然而sleep()之间的调用,却不能使线程中断。

一旦该程序被执行,它只会打印三个标准输出流。这是由于在main里3秒后调用 interrupt()方法。 因此,相应的线程被中断,并抛出一个 boost::thread_interrupted 异常。这个异常在线程内也被正确地捕获,catch 处理是空的。

Boost.Thread定义包括上述 sleep()函数等十个中断。 有了这些中断点,线程可以很容易及时中断。然而,他们并不总是最佳的选择,因为中断点必须事前读入以检查 boost::thread_interrupted 异常。

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

#include <iostream>

boost::mutex io_mutex;

using namespace std;

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

void interruptedThread()
{
	try
	{
		for (int i = 0; i < 5; i++)
		{
			wait(1);
			cout << i << endl;
		}
	}
	catch (boost::thread_interrupted&)
	{
		cout << "thread_interrupted exception happened";
	}
}

void testInteruptedThread()
{
	boost::thread t(interruptedThread);
	wait(3);
	t.interrupt();
	t.join();
}

int main(int argc, char* argv[])
{
	testInteruptedThread();
	return 0;
}

你可能感兴趣的:(thread,C++)