启动线程有detach()和join()两个函数,前者是异步启动,后者是同步启动并等待结束。
#include <iostream>
#include <thread>
struct task
{
int& i;
task(int& i_) :i(i_)
{};
void operator()()
{
for (int j = 0; j < 200; j++)
std::cout << "param is " << i << std::endl;
}
};
struct job
{
void operator()()
{
std::cout << "that is ok\n";
}
};
int main()
{
int a = 12;
task tk(a);
std::thread t(tk);
job j;
std::thread t2(j);
t2.detach();
t.join();
return 0;
}