代码
#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
总结
1 join()主线程等待子线程结束方可执行下一步(串行),
detach()是的子线程放飞自我,独立于主线程并发执行,主线程后续代码段无需等待。
2 在类内部创建线程,创建线程所在函数和传参的函数都要为static
遇到的问题
undefined reference to `pthread_create'
=》解决,编译带 -pthread 参数