学习资料
1 代码
#include<iostream>
#include<thread>
using namespace std;
void fun1(int a)
{
cout << "fun1(" << a << ")" << endl;
}
class demo
{
public:
void operator()(int a)
{
cout << "demo(" << a << ")" << endl;
}
};
int main()
{
cout << "cpu线程数:" << thread::hardware_concurrency() << endl;
thread t1(fun1, 3);
cout << "t1.get_id()=" << t1.get_id() << endl << "t1.joinable()=" << t1.joinable() << endl;
thread t2;
cout << "t2.get_id()=" << t2.get_id() << endl << "t2.joinable()=" << t2.joinable() << endl;
demo d;
t2 = move(thread(d, 4));
cout << "t2.get_id()=" << t2.get_id() << endl << "t2.joinable()=" << t2.joinable() << endl;
system("pause");
return 0;
}
2 运行结果及分析
分析主程序与fun1()函数可知,输出顺序为:
fun1函数的"fun1(" << a →主程序的 “t2.get_id()=" << t2.get_id() << endl → fun1函数的 “)” << endl; →主程序的 “t1.joinable()=” << t1.joinable() << endl;
说明主程序与线程t1在同时运行。同理,主程序与t2线程也是同时在运行。