Boost Thread

  [TOC]

设定线程可执行时间

#include <iostream>
using namespace std;

#include <boost/thread.hpp>

boost::thread t_time;

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

void thread()
{
	try
	{
		for (int i = 0; i < 5; ++i)
		{
			wait(1);
			std::cout << i << std::endl;
		}
	}
	catch (boost::thread_interrupted& )
	{
		printf("thread is interrupted\n");
	}
	
	printf("thread is over\n");
}

int main()
{
	t_time = boost::thread(thread);
	if (t_time.joinable())
	{
		printf("start therad success\n");

		t_time.timed_join(boost::posix_time::seconds(3));
		printf("time to interrupted\n");

		t_time.interrupt();
		t_time.join();

		printf("thread is over!!\n");
	}
	else
	{
		printf("start therad failed\n");
	}

	getchar();
	return 0;
}

解析: t_time.timed_join(boost::posix_time::seconds(3));线程执行3秒后,执行之后线程打断任务,之后等待线程结束。

参考

  1. boost::thread线程管理
posted @ 2021-01-14 18:58  采男孩的小蘑菇  阅读(253)  评论(0编辑  收藏  举报