c_cpp RAII处理线程生命周期的方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp RAII处理线程生命周期的方法相关的知识,希望对你有一定的参考价值。

/*
	Waiting for a thread to complete
*/

#include <thread>

struct Callable
{
	const int& _i;
	Callable(const int& i) : _i(i) 
	{}

	void operator()()
	{
		for (unsigned int j = 0; j < 1000000; j++)
		{
			do_something();
		}
	}

	void do_something()
	{
		// Do something
	}
};

struct thread_guard
{
	std::thread& _t;
	explicit thread_guard(std::thread& t) : _t(t)
	{}

	~thread_guard()
	{
		// Join can be called only once for a given thread
		if (_t.joinable())
		{
			_t.join();
		}
	}

	// Prevent creating copied of this object since copying the reference to the thread might be dangerous
	thread_guard(const thread_guard&) = delete;
	thread_guard& operator=(const thread_guard&) = delete;
};

void CreateThreads()
{
	int some_local_state;

	// Object with a reference to the local variable
	Callable c(some_local_state);

	std::thread t(c);

	// Thread guard will make sure that the function doesn't return without finishing the thread
	thread_guard g(t);
}

int main()
{
	CreateThreads();
}

以上是关于c_cpp RAII处理线程生命周期的方法的主要内容,如果未能解决你的问题,请参考以下文章

线程的生命周期

多线程的互斥锁应用RAII机制

多线程的互斥锁应用RAII机制

线程八大基础核心四(线程生命周期)

RAII思想之智能指针

在派生类中管理线程生命周期