1. 程式人生 > >boost執行緒中斷

boost執行緒中斷

/**
模擬功能:執行緒中斷  boost::this_thread::interruption_point()
一個對話方塊應用程式,介面上有兩個按鈕,一個是“開始”一個是“退出”,點選“開始”時建立一個執行緒,
這個執行緒會執行一個任務,whatever,可能是下載一個大檔案吧,然後在下載過程中需要在視窗上實時重新整理當前進度。
而在下載過程中“退出”按鈕隨時可能被點選,這時要求要先退出執行緒,再退出應用程式。
*/

#include "stdafx.h"
#include <windows.h>
#include <boost/thread.hpp>
#include <boost/bind.hpp>

using namespace std;
using std::tr1::shared_ptr;
class Downloader
{
public:
	Downloader() : m_percent(0) {}
	void start()
	{
		m_thread.reset(new boost::thread(boost::bind(&Downloader::download, this)));
		//m_thread->detach();此處不要detach 否則執行緒不可控 無法中斷
	}
	void stop()
	{
		m_thread->interrupt();
	}
	int get_percent() { return m_percent; }
private:
	void download()
	{
		try
		{
			while (m_percent < 100)
			{
				// 這是個中斷點
				boost::this_thread::interruption_point();
				++m_percent; // 模擬下載過程,加到100算結束
				// 這裡也是中斷點
				boost::this_thread::sleep(boost::posix_time::seconds(1));
				cout << "Percent is " << m_percent << endl;
			}
		}
		catch (boost::thread_interrupted& /*e*/)
		{
			//捕獲中斷點丟擲異常
			// 加上try-catch
			cout << "thread interrupted " << endl;
		}
	}
	shared_ptr<boost::thread> m_thread; // 下載程序
	int m_percent; // 下載百分比
};


int _tmain(int argc, _TCHAR* argv[])
{
	cout << "要開始下載檔案嗎?" << endl;
	char ch;
	if (cin >> ch && ch == 'y')
	{
		Downloader d;
		d.start();
		cout << "已經開始下載" << endl;
		cout << "要停止嗎?" << endl;
		if (cin >> ch && ch == 'y')
		{
			d.stop();
		}
		cout << "已經下載了%" << d.get_percent() << endl;
		Sleep(10000);
	}
	return 0;
}