std::thread yes C++ 11 The newly introduced standard thread library . In the same way C++ 11 Newly introduced lambda With the help of function ,std::thread It's very convenient to use :
int a = 1;
std::thread thread([a](int b) {
return a + b;
}, 2);
The only thing that's a little bit puzzling about it is that it provides join and detach function , It literally means that the former merges threads , The latter separates threads . Whether it's a merger or a separation , Will result in std::thread::joinable() return false, And before that, it was true( Even if the task of this new thread has been executed !).
The meaning of merging thread is clear , The binding thread is merged into the current thread for execution , The current thread is blocked , Until the merged thread is executed .
Separate threads are newly created threads and std::thread Object separation , The created thread runs independently .std::thread The thread will no longer be held . Some people may find this meaningless , But in theory there are still , Like after separation , We can deconstruct std::thread object , It doesn't affect the thread created ( The created thread will continue to run ).
int a = 1;
{
std::thread thread1([a](int b) {
return a + b;
}, 1);
thread1.detach();
}
{
std::thread thread2([a](int b) {
return a + b;
}, 2);
}
Take the above code for example ,thread1 No mistakes , but thread2 Will cause the program to exit . as a result of std::thread If the thread is not merged or detached , The program will exit automatically !
~thread() {
if (joinable()) std::terminate();
}
Its source code is located in https://gcc.gnu.org/onlinedocs/gcc-7.5.0/libstdc++/api/a00158_source.html, Implementation is very simple , Is based on pthread Encapsulation , Its content is only thread ID :
class thread {
public:
typedef __gthread_t native_handle_type;
class id {
native_handle_type _M_thread;
};
private:
id _M_id;
}
See here, are you right about “C++” I have a little new understanding ~
If you like this article , Move your little finger , Pay attention to it ~
Programming learning books :
Programming learning video :