c++ thread join用法
#include <thread>
#include <mutex>
#include <iostream>
using namespace std;
void downlaod1()
{
cout<<"d1"<<endl;
for (int i = 0; i < 100; ++i)
{
std::this_thread::sleep_for(chrono::milliseconds(50));
cout <<"下载进度1...."<< i<<endl;
}
cout <<"d1 successful!"<<endl;
}
void downlaod2()
{
cout<<"d2"<<endl;
for (int i = 0; i < 100; ++i)
{
std::this_thread::sleep_for(chrono::milliseconds(80));
cout<<"下载进度2...."<< i<<endl;
}
cout <<"下载完成2"<<endl;
}
void process()
{
cout <<"start process d1 and d2!\n"<<endl;
}
int main(int argc, char const *argv[])
{
cout<<"main run!\n";
thread d2(downlaod2);
downlaod1();
d2.join();
process();
return 0;
}
- g++ _thread_join.cpp -o test -lpthread
- -lpthread必须加上,不加会报thread_creat不存在的错误

从上面的结果看到,d2.join()的加入会使线程download1做完事情后,等待线程download2结束,共同执行process(),所以join()是必须等到线程执行完毕后返回
detach
#include <thread>
#include <iostream>
#include <mutex>
using namespace std;
void download1()
{
for (int i = 0; i < 100; ++i)
{
std::this_thread::sleep_for(chrono::milliseconds(5));
cout<<"d1 进度 ......"<< i<<endl;
}
cout<<"d1 sucessful!\n"<<endl;
}
void download2()
{
for (int i = 0; i < 100; ++i)
{
this_thread::sleep_for(chrono::milliseconds(5));
cout<<"d2 进度........"<<endl;
}
cout<<"d2 sucessful!\n"<<endl;
}
void process()
{
cout<<"d1 ok ,d2 ok"<<endl;
}
int main(int argc, char const *argv[])
{
cout<<"main run!\n"<<endl;
thread d1(download1);
thread d2(download2);
d1.detach();
d2.detach();
for (int i = 0; i < 5; ++i)
{
this_thread::sleep_for(chrono::milliseconds(15));
cout <<"main run process..."<< i<<endl;
}
process();
return 0;
}

对于join来说,detach使主线程和子线程并行,这样就不会应用join时候,带来的主线程阻塞的问题