文章目录
- cppman std::thread::detach
cppman std::thread::detach
std::thread::detach(3) C++ Programmer's Manual std::thread::detach(3)
NAME
std::thread::detach - Detach thread //分离线程
TYPE
public member function
SYNOPSIS
#include
void detach();
DESCRIPTION
Detaches the thread represented by the object from the calling thread, allowing them to execute independently from each other.
Both threads continue without blocking nor synchronizing in any way. Note that when either one ends execution, its resources are released.
After a call to this function, the thread object becomes non-joinable and can be destroyed safely.
//将对象表示的线程与调用线程分离,允许它们彼此独立执行。
//两个线程继续运行而不会以任何方式阻塞或同步。
//请注意,当任何一个结束执行时,都会释放其资源。
//调用此函数后,线程对象变得不可连接并且可以安全地销毁。
PARAMETERS
none
RETURN VALUE
none
EXAMPLE
#include // std::cout
#include // std::thread, std::this_thread::sleep_for
#include // std::chrono::seconds
void pause_thread(int n)
{
std::this_thread::sleep_for (std::chrono::seconds(n));
std::cout << "pause of " << n << " seconds endedn";
}
int main()
{
std::cout << "Spawning and detaching 3 threads...n"; //产生和分离 3 个线程
std::thread (pause_thread,1).detach();
std::thread (pause_thread,2).detach();
std::thread (pause_thread,3).detach();
std::cout << "Done spawning threads.n";
std::cout << "(the main thread will now pause for 5 seconds)n";
// give the detached threads time to finish (but not guaranteed!):
pause_thread(5);
return 0;
}
Output (after 5 seconds):
Spawning and detaching 3 threads...
Done spawning threads.
(the main thread will now pause for 5 seconds)
pause of 1 seconds ended
pause of 2 seconds ended
pause of 3 seconds ended
pause of 5 seconds ended
DATA RACES
The object is modified.
EXCEPTION SAFETY
Basic guarantee: if an exception is thrown by this member function, the thread object is left in a valid state.
If the call fails, a system_error exception is thrown:
+---------------+-------------------------------------------------------------------------------------------------------+-----------------------------------+
|exception type | error condition | description |
+---------------+-------------------------------------------------------------------------------------------------------+-----------------------------------+
|system_error | errc::invalid_argument | The thread object is not joinable |
+---------------+-------------------------------------------------------------------------------------------------------+-----------------------------------+
|system_error | errc::no_such_process | The thread object is not valid |
+---------------+-------------------------------------------------------------------------------------------------------+-----------------------------------+
SEE ALSO
thread::join(3)
Join thread (public member function)
thread::joinable(3)
Check if joinable (public member function)
REFERENCE
cplusplus.com, 2000-2015 - All rights reserved.
cplusplus.com 2022-05-13 std::thread::detach(3)
(END)