每个线程必须有一个初始函数,新线程开始于初始函数。可在std::thread()对象的构造函数中指定
示例程序由两个线程组成:初始线程始于main,新线程始于hello
新线程t的初始函数指定为hello
新线程启动后会与初始进程一并运行,初始线程可等待或不等待新进程的运行结束
如需等待线程则新线程实例需要使用join(),否则可以使用detach()
如不等待新线程,则初始线程自顾自地运行到main()结束
# include<iostream>
# include<thread>
using namespace std;
void hello()
{
cout<<"hello world"<<endl;
}
int main()
{
thread t (hello);
t.join();
}
网友评论