文章目录
简介
从C++11开始新增了很多新的库与特性。包括并发编程,之前windows上与linux上的线程开发的接口不同,移植起来特别麻烦,现在C++11中新增了thread库,使的能够同时运行在linux与windows上。
线程的创建
#include <iostream>
#include <thread>
using namespace std;
void Print()
{
cout << "hello ljw"<<endl;
}
class Threadclass
{
public:
int &my_i;
Threadclass(int& i) :my_i(i) {
cout << "构造函数" << endl;
}
Threadclass(const Threadclass &t) :my_i(t.my_i) {
cout << "拷贝构造函数" << endl;
}
~Threadclass() {
cout << "析构函数" << endl;
}
void t_thread(int i)
{
cout << “使用成员函数做线程”;
}
void operator()() {
cout << "创建一个新的线程" << endl;
}
};
int main()
{
int i;
/***********************************************************/
//用普通函数创新线程
std::thread mythread(Print);
//判断线程是否可以使用join与detach
if (mythread.joinable())
{
//阻塞等待子线程结束
//mythread.join();
//子线程与主线程分离,转为后台运行,子线程完成后,由运行时库负责清理该线程相关资源
mythread.detach();
}
/***********************************************************/
//使用类创建对象
Threadclass t(i); //执行构造函数
std::thread mythread2(t); //执行拷贝构造函数
mythread2.detach();
/***********************************************************/
//使用lambda表达式创建线程,auto的具体类型为std::function
auto mylamthread = [](){
cout << "lambda表达式" << endl;
};
std::thread mythread3(mylamthread);
mythread3.detach();
/***********************************************************/
//成员函数做线程
Threadclass t2(i);
std::thread mythread4(&Threadclass ::t_thread,t2,15);
mythread4.join();
std::cout << "Hello World!\n";
}
线程传参与线程id
- 线程传参
线程参数传递的参数是值传递,所以引用和指针会有问题
using namespace std;
class A
{
public:
int m_i;
A(int a) :m_i(a) {
cout << "构造函数" << endl; }
A(const A& a) :m_i(a.m_i) {
cout << "拷贝构造函数" << endl; }
~A() {
cout << "析构函数" << endl; }
};
//这里面使用const是因为thread传参是一个临时值是一个右值,不用const也可以使用右值引用
void myprint(const int i, const string &pmybuf)
{
cout << i << endl;
cout << pmybuf << endl;
return;
}
int main()
{
//普通函数传参
int mvar = 1;
char buf[] = "this is a test!";
//这个不使用隐式转换是为了防止buf在线程使用deatch时,主线程退出时还没有隐式转换成功,所以使用显示调用
thread mythread1(myprint, mvar, string(buf));
mythread1.detach();
}
- 线程id
可以使用std::this_thread::get_id();来获取
互斥量
互斥量mutex
- lock()与unlock()成对使用
struct Counter {
std::mutex mutex;
int value;
Counter() : value(0) {
}
void increment(){
mutex.lock();
++value;
mutex.unlock();
}
};
std::lock_guard
该类符号RAII(Resource Acquisition is Initialization)资源获取即初始化规则,有助于避免异常的情况。lock_guard不能进行手动解锁使得有点不方便
struct ConcurrentSafeCounter {
std::mutex mutex;
Counter counter;
void increment(){
std::lock_guard<std::mutex>