1. 程式人生 > >【C++】併發-1 執行緒管理-1

【C++】併發-1 執行緒管理-1

【建立】

有四種方式:

  1.  預設
  2. 傳入執行函式
  3. 定義一個類, 過載 operator() ,執行緒執行過程
  4. lambda
// std::thread 簡單使用
namespace T1
{
	template<class T>
	class ThreadPolicy
	{
	public:
		std::thread& Create()
		{
			return tmp.Create();
		}

	private:
		T tmp;
	};

	void ThreadFun()
	{
		std::cout << "create." << std::endl;
	}

	class MyThread
	{
	public:
		virtual std::thread& Create() = 0;
	};

	class Creater1 :public MyThread
	{
	public:
		std::thread& Create()
		{
			t = std::thread(ThreadFun);
			return t;
		}

		~Creater1()
		{
			std::cout << "create from function." << std::endl;
		}
	private:
		std::thread t;
	};

	class Creater2 :public MyThread
	{
	public:
		class F
		{
		public:
			void operator()()const
			{
				return ThreadFun();
			}
		};

		std::thread& Create()
		{
			t = std::thread(f);
			return t;
		}

		~Creater2()
		{
			std::cout << "create from class." << std::endl;
			t.join();
		}
	private:
		std::thread t;
		F f;
	};

	class Creater3 :public MyThread
	{
	public:
		Creater3() :t(std::thread()){}

		std::thread& Create()
		{
			t = std::thread([]()
			{
				ThreadFun();
			});

			return t;
		}

		~Creater3()
		{
			std::cout << "create from lambda" << std::endl;

			if (t.joinable())
				t.join();
		}

	private:
		std::thread t;
	};

	void Test()
	{
		ThreadPolicy<Creater3> tp;
		std::thread t = std::move(tp.Create());
 		t.join();

	}

}