代碼
#include <iostream>
#include <thread>
void foo()
{
std::cout<<"in foo \n";
}
void bar(int x)
{
std::cout<<"in bar"<<x<<std::endl;
}
int main()
{
std::thread first(foo);
std::thread second(bar, 99);
first.join();
second.detach();
std::cout<<"end of main\n";
return 0;
}
編譯
g++ -std=c++11 -pthread -o threadtest threadtest.cpp
輸出
li@ubuntu:~/testc11$ ./threadtest
in foo
in bar99
end of main
li@ubuntu:~/testc11$
li@ubuntu:~/testc11$ ./threadtest
in foo
end of main
li@ubuntu:~/testc11$ ./threadtest
in foo
in bar99
end of main
li@ubuntu:~/testc11$ ./threadtest
in foo
in barend of main
總結(jié)
1 join()主線程等待子線程結(jié)束方可執(zhí)行下一步(串行)申屹,
detach()是的子線程放飛自我渗柿,獨立于主線程并發(fā)執(zhí)行用僧,主線程后續(xù)代碼段無需等待蜘腌。
2 在類內(nèi)部創(chuàng)建線程,創(chuàng)建線程所在函數(shù)和傳參的函數(shù)都要為static
image.png
遇到的問題
undefined reference to `pthread_create'
=》解決拌牲,編譯帶 -pthread 參數(shù)