1 概述
添加此头文件可以直接调用线程相关的操作
#include <thread>
并且需要在对应的CMakeLists.txt编译中添加
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11 -pthread")
std::thread 默认构造函数,创建一个空的 std::thread 执行对象。
std::thread thread_object(callable)
它的调用对象可以是如下三种的任意一种:
- 函数指针
- 函数对象
- lambda表达式
程序源码示意如下:
#include <iostream>
#include <thread>
using namespace std;
void foo(int Z)
{
cout << "线程ID" << this_thread::get_id() << endl;
cout << "线程使用函数指针作为可调用参数 传入参数为 " << Z << endl;
}
// 可调用对象
class thread_obj {
public:
void operator()(int x)
{
cout << "线程ID" << this_thread::get_id() << endl;
cout << "线程使用可调用对象作为可调用参数 传入参数为 " << x << endl;
}
};
int main()
{
// 函数指针
thread th1(foo, 1);
// 函数对象
thread th2(thread_obj(), 2);
// 定义 Lambda 表达式
auto f = [](int x)
{
cout << "线程ID" << this_thread::get_id() << endl;
cout << "线程使用 lambda ";
for (int i = 0; i < x; i++)
{
cout << "i = " << i << "\t";
}
cout << endl;
};
thread th3(f, 3);
th1.join();
th2.join();
th3.join();
return 0;
}
上述实际打印的结果会比较乱。
而在实际项目上的使用往往会更加复杂。
2 实例
背景:
我这边有两个类.一个是blueEarModel从abstractModel中继承。
详细代码如下:
#include <iostream>
#include <thread>
#include <abstractModel.h>
#include <blueEarModel.h>
using namespace std;
int main()
{
//创建对应的线程
thread th1([]{
blueEarModel blueEarModelPri;
});
thread th2([]{
abstractModel abstractModelPri;
});
th1.join();
th2.join();
return 0;
}
这边通过匿名函数去创建两者的线程。
实际上打印出来的比较乱。
后面需要加相关的锁去操作。