C ++ 11 thread object thread

  • Thread class thread, providing creation and destruction RAII-style threads. When you create a code segment incoming thread thread to be executed (function, lamda expression) and the parameter, thread destructor will automatically destroy threads.

  • C ++ thread library to start by constructing a thread object a thread, the thread object to include context threads running time, such as: thread function, thread stack, the thread starting status and thread ID, etc. , all operations all encapsulated in a together, and finally passed to the underlying unity _beginthreadex () function to create a thread achieved (note: _beginthreadex is to create a thread in the bottom of windows c function).

  • std :: thread () to create a new thread can take any callable object types (with parameters or without parameters), including lambda expressions (with or without variable capture), function (global functions or member functions), function object.

Thread start: thread object constructor

By global function structure

#include<iostream>
#include<thread>
using std::cout;
using std::endl;
void threadRoute(int a,int b)
{
	cout << "I am a new thread of " << std::this_thread::get_id() << endl;
	cout << a + b << endl;
}
int main()
{
	int a = 10, b = 20;
	cout << "I am the main thread,and my thread id is " << std::this_thread::get_id() << endl;
	std::thread t(threadRoute,a,b);//thread对象构造函数指定线程执行函数
	t.join();//线程等待,防止出现孤儿线程
	system("pause");
}

By lamda expression construct

#include<iostream>
#include<thread>

using std::cout;
using std::endl;

int main()
{
	int a = 10, b = 20;
	cout << "I am the main thread,and my thread id is " << std::this_thread::get_id() << endl;
	std::thread t([=]{
		cout << "I am a new thread of " << std::this_thread::get_id() << endl;
		cout << a + b << endl;
	});
	t.join();//线程等待,防止出现孤儿线程
	system("pause");
}

By function object construction

#include<iostream>
#include<thread>

using std::cout;
using std::endl;

struct funcClass{
	void operator()(int a, int b)
	{
		cout << "ID:" << std::this_thread::get_id() << endl;
		cout << a + b << endl;
	}
};
int main()
{
	funcClass fc;//函数对象构造线程时候,必须先有函数对象,操作符不能是静态的
	std::thread t(fc, 10, 20);
	t.join();
	system("pause");
	return 0;
}

By a member Constructor

#include <iostream>
#include <thread>
using namespace std;
struct A
{
	static void memberFunc(int a,int b)
	{
		cout << "hello from class member function :" << this_thread::get_id() << endl;
		cout << a + b << endl;
	}
};
int main(int argc, char **argv)
{
	thread t1(A::memberFunc,10,20);
	t1.join();
	system("pause");
	return 0;
}

End of the thread

Create a thread, the default state is joinable state, needs the main thread to wait, if you do not want to wait to exit the thread, use the thread object member function to detach separate thread before the thread exits.

Join formula: join ()

join (): will take the initiative to terminate the waiting thread. Join in the call process (), when a new thread terminates, join () will clean up the associated resources, and then return to the calling thread and then continue down. Since join () to clean up the resources of threads, thread and thread objects have been destroyed there is no relationship, so every time you target a thread can only be used once join (), when you join the call () of joinable () it will be a false return.

#include<iostream>
#include<thread>
using std::cout;
using std::endl;
void threadRoute()
{
	cout << "ID:" << std::this_thread::get_id() << endl;
}
int main()
{
	cout << "Main ID:" << std::this_thread::get_id() << endl;
	std::thread t(threadRoute);//thread对象构造函数指定线程执行函数
	cout << t.joinable() << endl;//默认是joinable状态
	t.join();//线程等待,防止出现孤儿线程
	cout << t.joinable() << endl;//join一次就会把线程资源释放掉,现在已经是false了
	system("pause");
}

Separate: detach ()

detach: will sort out new thread from the calling thread parted after no longer interact with the new thread. Like you and your girlfriend broke up, after that you will not have contact (interaction), while after her resources consumption will not require you to pay a (clean up resources). At this point calls joinable () must be returned false. Separate thread thread into a daemon (orphaned), in Linux taken over by init, taken over by the library in c ++.

#include<iostream>
#include<thread>
using std::cout;
using std::endl;
void threadRoute()
{
	cout << "ID:" << std::this_thread::get_id() << endl;
}
int main()
{
	cout << "Main ID:" << std::this_thread::get_id() << endl;
	std::thread t(threadRoute);//thread对象构造函数指定线程执行函数
	cout << t.joinable() << endl;//默认是joinable状态
	t.detach();
	cout << t.joinable() << endl;//detach函数会将线程分离,不需要主线程join
	system("pause");
}

Note: You must make a choice before the thread object is destroyed, it is probably because the thread before you join or separate thread, it's over, go after separation if it is, the thread may continue to run down after thread object is destroyed.

Thread-safe thread

thread object can transfer ownership

Movable Object IS the Thread, not copyable, like std :: unique_ptr or std :: ifstream. std :: the Move can not move anything, its only function is to force the value into a left and right reference values, then we can through the right using this value reference value for moving semantics. From the perspective achieved, std :: move substantially equivalent to a type conversion: static_cast <T &&> (lvalue ); worth mentioning that the transformed value is left, not of its life with conversion values about changes. If the desired value of the variable std :: move left lvalue can be immediately transformed destructor, it will certainly be disappointed.

#include<iostream>
#include<thread>

using namespace std;
void some_function();

int main()
{
	thread t1(some_function); 
	thread t2 = move(t1); //采用std::move移动语义将t1的所有权移动到t2,
	//此时t2接管运行some_function(),而t1此时没有执行线程和其关联
	t1 = thread(some_function); //t1仍然是左值
}

Smart pointers thread object management

We know that the main thread after creating a new thread, the main thread should also need to do other things rather than just waiting for the other thread to exit. The main thread to do other things, before the join function, because the main thread may call another function caused by abnormal, so the main thread might miss the join function directly to the exception handling. Therefore, in order to ensure that the thread joinable state does not become an orphan process, you can thread a smart pointer to the object, a smart pointer join the destructor.

#include<iostream>
#include<thread>

using std::cout;
using std::endl;

void threadRoute()//全局函数
{
	cout << "ID:" << std::this_thread::get_id() << endl;
}
class Unique_ptr{
public:
	Unique_ptr(std::thread& t)//这里使用引用传参,传递的就是new出来的那一个线程对象
		:pt(t){}
	~Unique_ptr()
	{
		if (pt.joinable())
			pt.join();
	}
	Unique_ptr(const Unique_ptr&) = delete;
	Unique_ptr operator=(const Unique_ptr&) = delete;
private:
	std::thread& pt;
};

void func()
{
	cout << "Main ID:" << std::this_thread::get_id() << endl;
	std::thread t(threadRoute);
	Unique_ptr pth(t);
}//pth对象在此调用析构函数,调用线程join函数
int main()
{
	func();
	system("pause");
}

Guess you like

Origin blog.csdn.net/Vickers_xiaowei/article/details/89880893