首页 > 代码库 > C++11 thread::join(4)
C++11 thread::join(4)
原文地址:http://www.cplusplus.com/reference/thread/thread/join/
public member function
<thread>
std::thread::join
void join();
Join thread
The function returns when the thread execution has completed.当该线程执行完成后才返回。(即等待子线程执行完毕才继续执行主线程)
该函数的返回与子线程执行完毕同步,该函数会阻塞调用该函数的线程直到子线程调用完毕。
例子:
#include <iostream> #include <thread> #include <vector> #include <ctime> using namespace std; //delay(n) 延时n秒 void delay(double sec) { time_t start_time, cur_time; // 变量声明 time(&start_time); do { time(&cur_time); }while((cur_time - start_time) < sec ); }; void show(int n){ while(n>5){ cout<<"currentThread is "<<pthread_self()<<",Now n is "<<n<<endl; delay(1); n--; } } int main() { cout<<"main starts"<<endl; thread t2(show,10); //t2.join(); cout<<"main complete!"<<endl; }运行截图:
可以看到,t2还没有执行完毕就已经结束了。
加上t2.join()之后的执行结果:
可以看到,阻塞了主线程,等待t2执行完毕才继续执行main线程。
调用该函数后,子线程对象变成non-joinable以及可以安全地销毁。
Parameters
noneReturn value
noneExample
|
| Edit & Run |
Output (after 3 seconds):
Spawning 3 threads...
Done spawning threads. Now waiting for them to join:
pause of 1 seconds ended
pause of 2 seconds ended
pause of 3 seconds ended
All threads joined!
|
Data races
The object is modified.Note that any operations on the thread object itself are not synchronized (unlike the operations within the thread it represents).
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 |
system_error | errc::resource_deadlock_would_occur | - The current thread is the same as the thread attempted to join, or - A deadlock was detected (implementations may detect certain cases of deadlock). |
Note that if the thread represented by the object terminates with an uncaught exception, this cannot be caught by the current thread, and terminate()
is automatically called.
—————————————————————————————————————————————————————————————————
//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。
转载请注明出处:http://blog.csdn.net/qq844352155
author:天下无双
Email:coderguang@gmail.com
2014-9-4
于GDUT
——————————————————————————————————————————————————————————————————
C++11 thread::join(4)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。