第六章:并发与多线程

156 阅读1小时+

第一节

todo: 待补充

第二节:线程启动、结束、创建多线程方法、join、delete

2.1 范例演示线程运行的开始和结束

程序运行起来,生成一个进程,该进程所属的主线程开始自动运行。

#include <iostream>
using namespace std;
int main() {
    // 实际上这个是主线程在执行,主线程从main函数返回,则整个进程执行完毕。
    cout << "主线程执行完毕" << endl;
    return 0;
}

主线程从main开始执行,那么我们自己创建的线程,也需要从一个函数开始执行(初始函数),一旦这个函数运行完毕,就代表着我们这个线程运行结束。 整个进程是否执行完毕的标志是:主线程是否执行完,如果主线程执行完毕了,就代表整个进程执行完毕了,此时,一般情况下:如果其他子线程还没有执行完毕,那么这些子线程也会被操作系统强行终止。所以一般情况下,我们得到一个结论:如果大家想保持子线程(自己用代码创建的线程)的运行状态的话,那么大家要让主线程一直保持运行,不要让主线程退出。【这条规律有例外】 如果主线程执行完毕,但子线程没有执行完毕,写出来的程序是不合格且不稳定的。 一个书写良好的程序,应该是主线程等待子线程执行完毕后,自己才能最终退出。

如何创建多线程

a)一个头文件thread要包含进来

#include <thread>

b) 自己创建的线程要从一个函数(也叫初始函数)开始执行

c) main函数中开始写代码

#include <iostream>
#include <thread>
using namespace std;
void my_print() {
    cout << "我的线程开始执行" << endl;
    //...其他逻辑
    cout << "我的线程执行完毕了" << endl;
}

int main() {
    thread sub_thread(my_print);
    sub_thread.join();
    cout << "主线程执行完毕" << endl;
    return 0; // 主线程执行完毕,退出
}

运行结果

我的线程开始执行
我的线程执行完毕了
主线程执行完毕

上面的程序有两个线程在跑,相当于整个程序的执行有两条线同时走,所以可以同时干两个事。即使一条线被堵住了,也不耽误另一条线的运行。

image.png

2.1.1 thread

thread是标准库中的类,thread函数接收一个可调用对象。

thread sub_thread(my_print); // my_print是可调用对象

上面这句代码的作用如下: (1) 创建了线程,线程执行起点(入口)是my_print() (2) 是my_print线程开始执行

2.1.2 join()

join(): 加入 / 汇合,说白了就是阻塞,阻塞主线程,让主线程等待子线程执行完毕,然后子线程和主线程汇合。然后主线程再往下走。

sub_thread.join();

执行到上面这句代码时,主线程会阻塞到这里等待my_print()执行完,当子线程执行完毕,这个join()就执行完毕,主线程就继续往下走。

2.1.3 detach()(不推荐使用)

传统多线程主线程要等待子线程执行完毕,自己在最后退出。

detach:分离,也就是主线程不和子线程汇合了,主线程和子线程各自执行,主线程不必等待子线程运行结束,主线程可以先执行结束,这并不影响子线程的执行。

一旦调用detach()之后,与这个主线程关联的thread对象就会失去与这个主线程的关联,此时子线程就会驻留在后台运行(主线程与该子线程失去联系),这个子线程就相当于被c++运行时库接管了。当这个子线程运行执行完成后,由运行时库负责清理该线程相关的资源(守护线程)。

引入detach()原因: 有一种理论任务代码中创建了很多子线程,让主线程逐个等待子线程结束,这种编程方法不好。

不推荐使用detach()原因: 让主线程等待子线程执行完毕后再退出可以保持程序稳定。使用detach可能增加很多困扰。

#include <iostream>
#include <thread>
using namespace std;
void my_print() {
    cout << "我的线程开始执行" << endl;
    //...其他逻辑
    cout << "我的线程执行完毕了1" << endl;
    cout << "我的线程执行完毕了2" << endl;
    cout << "我的线程执行完毕了3" << endl;
    cout << "我的线程执行完毕了4" << endl;
}

int main() {
    thread sub_thread(my_print);
//    sub_thread.join();
    sub_thread.detach();
    cout << "主线程执行完毕1" << endl;
    cout << "主线程执行完毕2" << endl;
    return 0;
}

执行结果

主线程执行完毕1
我的线程开始执行
我的线程执行完毕了1
主线程执行完毕2
我的线程执行完毕了2

因为主线程输出完主线程执行完毕2后就退出了,因此上面程序的9、10行即我的线程执行完毕了3我的线程执行完毕了4没有办法输出。子线程后续被c++运行时库接管。

一旦调用了detach,就不能再用join,否则会有异常。

2.1.4 joinable()

joinable()作用:判断是否可以成功使用join或者detach。

返回值:true(可以join或者detach),false(不可以join或者detach)

2. 其他创建线程的手法

2.2.1 用类(可调用对象)、以及一个问题范例

#include <iostream>
#include <thread>

using namespace std;

class MyThread {
public:
    void operator()() { // 不能带参数
        cout << "我的线程operator()开始执行了" << endl;
        //  ...
        cout << "我的线程operator()结束执行了" << endl;
    }
};

int main() {
    MyThread my_thread;
    // my_thread可调用对象
    // my_thread是主线程的局部变量,但被【复制】到子线程中去
    thread sub_thread1(my_thread); 
    sub_thread1.join(); // 等待子线程执行结束
    cout << "主线程执行完毕" << endl;
    return 0;
}

执行结果

我的线程operator()开始执行了
我的线程operator()结束执行了
主线程执行完毕

查看构造函数、拷贝构造函数、析构函数调用情况

#include <iostream>
#include <thread>

using namespace std;

class MyThread {
public:
    int &num;

    MyThread(int &i) : num(i) {
        cout << "MyThread()构造函数被执行,线程ID:" << this_thread::get_id() << endl;
    }

    MyThread(const MyThread &my_thread) : num(my_thread.num) {
        cout << "MyThread()拷贝构造函数被执行,线程ID:" << this_thread::get_id() << endl;
    }

    ~MyThread() {
        cout << "MyThread()析构函数被执行,线程ID:" << this_thread::get_id() << endl;
    }

    void operator()() { // 不能带参数
    }
};

int main() {
    int num = 6;
    cout << "主线程id: " << this_thread::get_id() << endl;
    MyThread my_thread(num); // 执行构造函数
    thread sub_thread1(my_thread); // 执行拷贝构造函数
    sub_thread1.join(); // 等待子线程执行结束
    cout << "主线程执行完毕" << endl;
    return 0;
}

执行结果

主线程id: 0x104754580
MyThread()构造函数被执行,线程ID:0x104754580
MyThread()拷贝构造函数被执行,线程ID:0x104754580
MyThread()拷贝构造函数被执行,线程ID:0x104754580
MyThread()析构函数被执行,线程ID:0x104754580
MyThread()析构函数被执行,线程ID:0x16baaf000
主线程执行完毕
MyThread()析构函数被执行,线程ID:0x104754580 // 调用析构函数释放my_thread

在使用gcc作为编译器时,会累计会调用2次拷贝构造函数和2次析构函数。在给thread传参数时会调用拷贝构造函数,当然也就有一次析构函数被调用。多出来的1次拷贝构造函数和析构函数的调用没想明白...(下面是相关解释,依旧没有完全看明白)

StackOverFlow:stackoverflow.com/questions/3…

cppreference:en.cppreference.com/w/cpp/threa…

2.2.2 用lambda表达式

#include <iostream>
#include <thread>

using namespace std;

int main() {
    auto my_lambda = []() -> void {
        cout << "lambda开始执行" << endl;
        cout << "lambda结束执行" << endl;
    };
    thread my_thread(my_lambda);
    my_thread.join();
    cout << "主线程执行完毕" << endl;
    return 0;
}

执行结果

lambda开始执行
lambda结束执行
主线程执行完毕

第三节:线程传参详解、detach()大坑、成员函数做线程参数

3.1 传递临时对象作为线程参数

3.1.1 使用detach要避免的陷阱

#include <iostream>
#include <thread>

using namespace std;

void my_print(const int &i, char *buf) {
    // i不是下面my_var的引用,实际上是值传递
    // 即使主线程detach了子线程,子线程中用my_var的值也是安全的。
    cout << i << endl;
    // 指针在detach子线程时,绝对有问题
    cout << buf << endl;
}

int main() {
    int var = 1;
    int &my_var = var;
    char buf[] = "this is a test!";
    thread my_thread(my_print, my_var, buf);
//    my_thread.join();
    my_thread.detach();
    return 0;
}

上面代码中,my_print的buf传递的是指针,在mian函数中调用时,因为子线程使用detach执行,因此若主线程在子线程执行之前完成执行,则17行buf指针对应的内存地址将会被回收,从而带来难以预料的结果。

void my_print(const int &i, const string& buf) {
    // i不是下面my_var的引用,实际上是值传递
    // 即使主线程detach了子线程,子线程中用my_var的值也是安全的。
    cout << i << endl;
    // 指针在detach子线程时,绝对有问题
    cout << buf.c_str() << endl;
}

若将my_print改成上面的形式,则在 thread my_thread(my_print, my_var, buf)中调用时,会将char[]类型的buf转换成string,但转换时机不一定,事实上存在一种可能,buf都已经被回收了(main函数执行完毕),系统才用buf转换成string。

实际上,若要让程序稳定,除了要把char *buf改成const string& buf,还需要将main函数中的18行改为thread my_thread(my_print, my_var, string(buf));,原因是在直接将buf转成string对象,可以保证线程中使用的buf一定稳定。 下面进行一些测试来验证上面的说法

#include <iostream>
#include <thread>

using namespace std;

class A {
public:
    int num;

    // 类型转换构造函数,可以把一个int转换成类A对象
    A(int a) : num(a) {
        cout << "A::(int a)构造函数执行" << endl;
    }

    A(const A &a) : num(a.num) {
        cout << "A::(int a)拷贝构造函数执行" << endl;
    }

    ~A() {
        cout << "A::(int a)析构函数执行" << endl;
    };
};

void my_print(const int &i, const A &buf) {
    cout << &buf << endl; // 这里打印的是buf的地址
}

int main() {
    int var = 1;
    int tmp = 12;
    thread my_thread(my_print, var, tmp);
    my_thread.detach();
    return 0;
}

执行上面代码无任何输出,说明在主线程退出后,使用的tmp也没有被构造成类A的对象供my_print使用,则tmp构造成类A的对象发生在主线程执行完毕之后,但此时tmp对应的内存空间已经被回收,此时使用已经被回收的空间构造类A的对象肯定会导致未定义的行为。

将上面代码的31行修改如下:

thread my_thread(my_print, var, A(tmp));

执行结果如下:

A::(int a)构造函数执行
A::(int a)拷贝构造函数执行
A::(int a)拷贝构造函数执行
A::(int a)析构函数执行
A::(int a)析构函数执行

基于执行结果,可以得到如下结论:只要用临时构造的A类对象作为参数传递给线程,那么就一定能够在主线程执行完毕前把线程函数的参数构造出来,从而确保即便detach()了,子线程也安全运行。

在使用detach的情况下,有如下结论:

  1. 若传递int这种简单类型参数,建议都是值传递,不要用引用。
  2. 若传递类对象,避免隐式类型转换。全部都在创建线程这一行构建临时对象,在函数参数里用引用来接受。
  3. 建议不使用detach,只使用join不会产生局部变量失效导致线程对内存的非法引用问题。

3.1.2 线程id的概念

每个线程都对应一个唯一的线程id,可以使用c++标准库中的std::this_thread::get_id()来获取线程id。

3.1.3 临时对象构造时机抓捕

#include <iostream>
#include <thread>

using namespace std;

class A {
public:
    int num;
    // 类型转换构造函数,可以把一个int转换成类A对象
    A(int a) : num(a) {
        cout << "A::(int a)构造函数执行, 线程id: " << this_thread::get_id() << endl;
    }

    A(const A &a) : num(a.num) {
        cout << "A::(int a)拷贝构造函数执行, 线程id: " << this_thread::get_id() << endl;
    }

    ~A() {
        cout << "A::(int a)析构函数执行, 线程id: " << this_thread::get_id() << endl;
    };
};

void my_print2(const A &buf) {
    cout << "子线程my_print2的参数地址是" << &buf << " 线程id: " << this_thread::get_id() << endl; // 这里打印的是buf的地址
}

int main() {
    cout << "主线程id: " << this_thread::get_id() << endl;
    int tmp = 12;
    thread my_thread(my_print2, tmp);
    my_thread.join();
    return 0;
}

执行结果如下:

主线程id: 0x100540580
A::(int a)构造函数执行, 线程id: 0x16fd5f000
子线程my_print2的参数地址是0x16fd5ef3c 线程id: 0x16fd5f000
A::(int a)析构函数执行, 线程id: 0x16fd5f000

从执行结果可以看出来,my_print2完成了对tmp参数的隐式转换(由int转换成类A),将tmp构造成A类对象的工作是在子线程中完成的。 将上述代码的30行进行修改

thread my_thread(my_print2, A(tmp));

执行结果如下

主线程id: 0x102e70580
A::(int a)构造函数执行, 线程id: 0x102e70580
A::(int a)拷贝构造函数执行, 线程id: 0x102e70580
A::(int a)拷贝构造函数执行, 线程id: 0x102e70580
A::(int a)析构函数执行, 线程id: 0x102e70580
A::(int a)析构函数执行, 线程id: 0x102e70580
子线程my_print2的参数地址是0x6000019b5130 线程id: 0x16d1bb000
A::(int a)析构函数执行, 线程id: 0x16d1bb000

使用临时对象后,A类对象在main函数构建完毕。

3.2 传递类对象、智能指针作为线程参数

传递类对象作为线程参数

为了数据安全考虑,向线程中传递参数时,无论是用引用接收还是用值接收,编译器都会统一按照拷贝的方式来进行参数的接收(拷贝构造函数会执行)。如果真的需要传递引用,需要使用std::ref

传递智能指针作为线程参数

#include <iostream>
#include <thread>

using namespace std;

void my_print3(unique_ptr<int> ptr) {
    cout << "子线程my_print2的参数地址是" << " 线程id: " << this_thread::get_id() << endl; // 这里打印的是buf的地址
}

int main() {
    unique_ptr<int> my_ptr(new int(100));
    thread my_thread(my_print3, std::move(my_ptr));
    my_thread.join();
    return 0;
}

3.3 用成员函数指针做线程函数

第四节:创建多个线程、数据共享问题分析、案例代码

4.1 创建和等待多个线程

  1. 多个线程同时执行时,执行顺序是乱序,与操作系统内部对线程的运行调度机制有关。
  2. 使用join后主线程等待所有子线程运行结束,最后主线程运行结束。
  3. 把thread对象放入到容器里管理,看起来像一个thread数组,这对于我们一次创建大量的线程并对大量线程进行管理来说很方便。
#include <iostream>
#include <thread>
#include <vector>

using namespace std;

void my_print(int num) {
    cout << "线程开始执行了,线程编号 = " << num << endl;
    // 其他事情
    cout << "线程结束执行了,线程编号 = " << num << endl;
}

int main() {
    // 创建和等待多个线程
    vector<thread> my_threads;
    // 创建10个线程,线程入口函数统一使用 my_print
    int thread_num = 5;
    my_threads.reserve(thread_num);
    for (int i = 0; i < thread_num; ++i) {
        my_threads.emplace_back(my_print, i); // 创建并开始执行线程
    }
    for (auto & my_thread : my_threads) {
        my_thread.join();// 等待线程都返回
    }
    cout << "主线程执行结束" << endl; // 最后执行这句,整个进程退出
    return 0;
}

执行结果

线程开始执行了,线程编号 = 0
线程结束执行了,线程编号 = 0
线程开始执行了,线程编号 = 1线程开始执行了,线程编号 = 2
线程结束执行了,线程编号 = 2
线程开始执行了,线程编号 = 4
线程结束执行了,线程编号 = 4
线程开始执行了,线程编号 = 3
线程结束执行了,线程编号 = 3

线程结束执行了,线程编号 = 1
主线程执行结束

4.2 数据共享问题分析

4.2.1 数据只读

数据只读是安全稳定的,不需要特别的处理手段。

4.2.2 数据有读有写

4.2.3 其他案例

第五节:互斥量概念、用法、死锁演示及解决详解

5.1 互斥量(mutex)的基本概念

互斥量是个类对象,理解成一把锁,多个线程尝试用lock()成员函数加锁,只有一个线程能够加锁成功(成功的标志是lock函数返回,如果没锁成功,那么流程会被阻塞在lock()这里,lock()会这里不断尝试加锁)。

5.2 互斥量用法

5.2.1 lock()与unlock()

lock()与unlock()使用顺序:

  1. 先lock()
  2. 操作共享数据
  3. unlock() lock()和unlock()要成对使用,

注意:有lock()必然要有unlock(),每调用一次lock(),必然应该调用一次unlock()。不应该也不允许调用1次lock()却调用多次unlock(),也不允许调用多次lock()却调用1次unlock(),这些非对称数量的调用都会导致程序崩溃。

使用lock()与unlock()示例代码

#include <iostream>
#include <thread>
#include <vector>
#include <list>
#include <mutex>

using namespace std;

vector<int> g_v = {1, 2, 3}; // 共享数据

class A {
public:

    bool out_msg_proc(int &command) {
        my_mutex.lock();
        if (!msgRecvQueue.empty()) {
            // 消息不为空
            // 返回第一个元素,但不检查元素是否存在
            command = msgRecvQueue.front();
            // 移除第一个元素,但不返回
            msgRecvQueue.pop_front();
            my_mutex.unlock();
            return true;
        }
        my_mutex.unlock();
        return false;
    }

    // 把数据从消息队列中取出的线程
    void out_msg_recv_queue() {
        int command = 0;
        for (int i = 0; i < 100000; ++i) {
            bool res = out_msg_proc(command);
            if (res) {
                cout << "out_msg_recv_queue()执行,取出一个元素: " << command << endl;
                // 可以考虑处理数据
            } else {
                // 消息队列为空
                cout << "out_msg_recv_queue()执行,但目前消息队列中为空" << i << endl;

            }
        }
    }

    // 把收到的消息入到一个队列的线程
    void in_msg_recv_queue() {
        for (int i = 0; i < 100000; ++i) {
            cout << "in_msg_recv_queue()执行,插入一个元素 " << i << endl;
            my_mutex.lock();
            msgRecvQueue.push_back(i);
            my_mutex.unlock();
        }
    }

private:
    std::list<int> msgRecvQueue; // 容器(消息队列)代表玩家给服务器发送的指令
    std::mutex my_mutex; // 互斥量
};


int main() {
    A my_obj;
    std::thread my_out_msg(&A::out_msg_recv_queue, &my_obj);
    std::thread my_in_msg(&A::in_msg_recv_queue, &my_obj);
    my_out_msg.join();
    my_in_msg.join();
    return 0;
}

5.2.2 std::lock_guard类模板

为了防止大家忘记unlock(),引入了一个叫std::lock_guard的类模板

std::lock_guard类模板:直接取代lock()与unlock(),也就是说,用了std::lock_guard以后,不能再使用lock()和unlock()

lock_guard构造函数里执行了mutex::lock(),析构函数里执行了mutex::unlock()

5.3 死锁

5.3.1 死锁的一般解决方案

5.3.2 std::lock()函数模板

能力:一次锁住两个或者两个以上的互斥量(至少两个,多了不限,1个不行)

使用std::lock()不存在因为在多个线程中,因为锁的顺序问题导致死锁的风险问题。

如果互斥量中有一个没锁住,它就在那里等着,等所有互斥量都锁住,它才能往下走(返回)。

要么两个互斥量都锁住,要么两个互斥量都没锁住,如果只锁了一个,另一个没锁成功,则它立即把已经锁住的解锁。

总结:std::lock()一次锁住多个互斥量,谨慎使用(建议一个一个锁)

5.3.3 std::lock_guard()的std::adopt_lock参数

std::adopt_lock是一个结构体对象,起一个标记作用:作用就是表示这个互斥量已经lock(),不需要在std::lock_guard()std::mutex构造函数里面对mutex对象进行lock()了.

第六节:unique_lock详解

unique_lock取代lock_guard

unique_lock: 是一个类模板,它也能帮助我们自动管理(自动加锁和解锁)mutex互斥量的lock()和unlock()操作(构造函数中lock mutex,析构函数中unlock mutex)。lock_guard这个类模板可以帮助我们自动管理互斥量mutex的lock()和unlock()。这个unique_lock也是类似的。但是,unique_lock比lock_guard在用法上还要更加灵活一些。

使用格式(与lock_guard一致):

std::unique_lock<std::mutex> uniquelockObjName(mutexObjName);
  • 注意1:在工作当中,一般推荐使用lock_guard。
  • 注意2:unique_lock虽然使用上比lock_guard灵活,但效率上比lock_guard低,占用内存空间也会多一点。

unique_lock的第二个参数

unique_lock类模板所支持的第2个参数,可以帮助其完成一些额外的功能。

std::adopt_lock

使用格式

std::unique_lock<std::mutex> uniquelockObjName(mutexObjName,std::adopt_lock);

解释:

  1. 前提:该互斥量必须提前被lock(互斥量.lock())(否则会报异常)
  2. 表示该互斥量已经被lock(),即不需要在unique_lock的构造函数中lock这个互斥量了
  3. lock_guard中也可以用这个参数
void inMsgRecvQueue() {
	my_mutex.lock();
    //提前lock该my_mutex互斥量,后续才能让unique_lock的std::adopt_lock参数
    //在调用其构造函数时不再lock该互斥量了
	std::unique_lock<std::mutex> sbguard1(my_mutex,std::adopt_lock);
	for (int i = 0; i < 10000; i++) {
		cout << "inMsgRecvQueue()执行,插入一个元素: " << i << endl;
		msgRecvQueue.push_back(i);//假设这个数字i就是我收到的命令
	}
	return;
}

std::try_to_lock

std::try_to_lock参数: 会使得unique_lock类模板的构造函数会尝试用mutex的lock()去锁定这个mutex,如果没有锁定成功,会立即返回,不会阻塞在那里;使用try_to_lock的原因是防止其他的线程锁定mutex太长时间,导致本线程一直阻塞在lock这个地方。 使用格式

std::unique_lock<std::mutex> uniquelockObjName(mutexObjName,std::try_to_lock);

解释

  1. 前提:不能将该mutex互斥量提前lock();(否则会报异常)
  2. unique_lock类对象的.owns_lock()方法可判断是否拿到锁(上锁了),如拿到返回true,拿不到这个锁,则返回false

std::defer_lock

defer_lock参数:会使得mutex延迟lock,也即unique_lock类调用构造函数时会创建一个没有被lock的mutex。当然,后续你可以直接调用unique_lock的类对象将对应mutex lock上!

使用格式:

std::unique_lock<std::mutex> uniquelockObjName(mutexObjName,std::defer_lock);

解释:

  1. 前提:不能将该mutex互斥量提前lock();(否则会报异常)
  2. unique_lock如果没有第二个参数时,就会对mutex进行加锁,如果第2参数是defer_lock,则会始化一个没有加锁的mutex (也即unique_lock类调用构造函数时会创建一个没有被lock的mutex)
  3. 不给它加锁的目的是以后用该尚未加锁的mutex互斥量调用unique_lock的一些成员函数(这就体现出来unique_lock类模板的灵活性了)

unique_lock的成员函数

使用unique_lock的成员函数的前提 必须将unique_lock类对象的第2个参数设置为std::defer_lock。即必须有以下这行代码才能使用unique_lock这个类模板的各个成员函数:

std::unique_lock<std::mutex> uniquelockObjName(mutexObjName, std::defer_lock);

lock()与unlock()

  • lock():用unique_lock的对象给对应的mutex加锁!
  • unlock():用unique_lock的对象给对应的mutex解锁!

解释: 用到unique_lock中的.unlock()成员函数的情况通常都是:当你需要在线程函数中处理一些非共享代码时,就要手动对象.unlock(),然后处理非共享代码。但注意:处理完毕后必须要手动再lock上,否则就很有可能会报异常!

//线程函数中
...
std::unique_lock<std::mutex> sbguard1(my_mutex, std::defer_lock);//try_to_lock
//defer_lock参数会使得mutex延迟lock,也即unique_lock类调用构造函数时会创建一个没有被lock的mutex
//当然,后续你可以直接调用unique_lock的类对象将对应mutex lock上!
sbguard1.lock();
//处理共享代码(用锁来保护线程中的共享代码)
sbguard1.unlock();
//处理一些非共享代码(无需用锁来保护的线程中的非共享代码)
//处理完毕之后,再手动上锁
sbguard1.lock();
//if后续还有共享代码,则
//继续处理共享代码(用锁来保护线程中的共享代码)
...

try_lock()

尝试去给mutex加锁!加锁成功返回true,失败则返回false!且加锁失败也不会让该子线程一直阻塞在这儿。 解释:其实,unique_lock类对象的成员函数.try_lock()的作用与上述所说的std::try_to_lock参数+其类对象的.owns_lock()成员函数的作用是一致的!

//线程函数中:
...
std::unique_lock<std::mutex> sbguard1(my_mutex);
if (sbguard1.try_lock()) {
    //处理共享代码...
}else{
    //...
}
...
 
// ==> 相当于
 
//线程函数中:
...
std::unique_lock<std::mutex> sbguard1(my_mutex,try_to_lock);//
if (sbguard1.owns_lock()) {
    //处理共享代码...
}else{
    //...
}
...

release()

unique_lock<std::mutex> uniquelockObj(mutexObj)

解释:上面这行代码相当于把mutex对象mutexObj和unique_lock对象uniquelockObj绑定在了一起。 (大白话:将unique_lock对象与mutex对象的关系绑一起了!)

release()的作用:解除绑定,返回unique_lock对象所管理的mutex对象的指针,并释放其原来拥有的对于mutex对象的所有权。(简记为:返回mutex对象指针,并释放所有权)

mutex* ptx = uniquelockObj.release();

注意: 如果原来mutex对象处于加锁状态并未unlock,则需要你有责任接管过来并手动用ptx进行解锁。

补充知识:

  1. 为什么有时需要unlock:因为你lock锁住的代码越少,你程序执行得越快,整个程序的运行效率就高!

  2. 有人把锁头锁住的代码多少,称之为锁的粒度。(粒度一般用粗细来描述)

    2.1:锁住的共享数据的代码少,叫作粒度细,执行效率高; 2.2:锁住的共享数据的代码多,叫作粒度粗,执行效率低;

As a result,必须学会用合适粒度的代码对共享数据进行保护。若粒度太细,则可能会漏掉对于共享数据的保护,粒度太粗,则会影响代码效率。(选择好粒度的能力,需要多coding多写多练)

unique_lock所有权的传递

std::unique_lock<std::mutex> sbguard1(my_mutex);
//此时sbguard1这个unique_lock对象与my_mutex这个互斥量绑定到一起了
//称之为sbguard1拥有了my_mutex的所有权

unique_lock对象的所有权可以转移,但不能拷贝(复制)

image.png 所有权转移的方法有2种:

  1. 使用std::move移动语义来进行所有权转移
std::unique_lock<std::mutex> sbguard1(my_mutex);
std::unique_lock<std::mutex> sbguard2(std::move(sbguard1));
//使用std::move()函数:
//先让sbguard1指向空(==> 相当于sbguard1.release()了!sbguard1与my_mutex解绑了!)
//然后sbguard2再绑定到my_mutex这个互斥量上
//现在sbguard2就拥有了my_mutex的管理所有权
  1. 在函数中return一个临时的std::unique_lockstd::mutex变量,即可实现转移:
std::unique_lock<std::mutex> ret_unique_lock() {
	return std::unique_lock<std::mutex>(my_mutex);
}
// or
std::unique_lock<std::mutex> ret_unique_lock() {
    std::unique_lock<std::mutex> tmp(my_mutex);
    //移动构造函数那一节讲过,从函数返回一个局部的unique_lock对象是可以的
    //返回这种局部对象会导致系统生成临时的匿名unique_lock对象,并调用unique_lock的移动构造函数
    //将这个临时匿名对象所管理的mutex的权限移动给返回的对象。	
    return tmp;
}
//线程函数入口
void inMsgRecvQueue() {
    //...
    std::unique_lock<std::mutex> sbguard1 = ret_unique_lock();
    //...
}

第七节:单例设计模式共享数据问题的分析和解决,call_once

设计模式大概谈

所谓“设计模式”,指的是代码的一些写法(这些写法与常规的写法不一样)。它会使得程序变得灵活,维护起来可能方便。但用设计模式理念写出来的代码很晦涩,别人接管、阅读代码都会很痛苦,需要下很大功夫才能搞懂。设计模式最先是老外应付特别大的项目时,把项目的开发经验、模块划分经验,总结整理而成的。零几年设计模式在中国刚开始火时,程序员们总喜欢拿一个设计模式往项目代码上套,导致一个小小的项目总要加几个设计模式,这就本末倒置了。但不可否认的是,设计模式有其独特的优点,作为程序员,一定要活学活用,不要深陷其中,生搬硬套!

单例设计模式(常用)

在整个项目中,有某个或者某些特殊的类,只能创建一个属于该类的对象。这即为单例设计模式。
单例类:只能生成该类的一个对象。

#include<iostream>
using namespace std;
//单例类例子codes
class MyCLS {
private:
	MyCLS(){}//私有化类的构造函数时,类外部就不可以用className ObjName的方式来创建类的对象了。
private:
	static MyCLS* m_instance;//静态成员变量必须是类内声明,类外初始化
public:
	static MyCLS* getInstance() {
		if (m_instance == nullptr) {
			m_instance = new MyCLS();
			static CGarHuishou cl;
            //静态局部变量 <==> 全局变量(在整一个程序运行结束时,其作用域才end)
            //so才可以用另外一个类来帮助我delete上述在heap区开辟内存空间的m_instance指针
		}
		//shared_ptr<MyCLS>(make_shared())
		return m_instance;
	}
	void func() {
		static int nums = 0;
		nums++;
		cout << "test codes " <<nums<< endl;
	}
 
	class CGarHuishou {//类中嵌套另一个类,这个类专门用于析构单例类中的new的对象所占据的内存空间!
	public:
		~CGarHuishou() {
			if (MyCLS::m_instance) {//非空 再delete,若本来就是空则不要重复delete
				delete MyCLS::m_instance;
				MyCLS::m_instance = nullptr;
				cout << "~CGarHuishou()执行了!" << endl;
			}
		}
	};
};
//静态成员变量必须是类内声明,类外初始化
MyCLS* MyCLS::m_instance = nullptr;
int main(void) {
	MyCLS* weiyiObj = MyCLS::getInstance();//因为是static成员,所以要用::符号来使用该函数!
	MyCLS* weiyiObj2 = MyCLS::getInstance();//因为是static成员,所以要用::符号来使用该函数!
	weiyiObj->func();
	weiyiObj2->func();
	MyCLS::getInstance()->func();
    if (weiyiObj == weiyiObj2)cout << "weiyiObj == weiyiObj2" << endl;
	else cout<< "weiyiObj != weiyiObj2" << endl;
    //从运行结果来看,这2个指针都指向同一块内存,说明只可以产生一个该类的对象!
    //也即,实际上,都只是产生了一块内存而已!
	return 0;
}

运行结果:

image.png

双重检查加锁单例模式为什么两次校验:blog.csdn.net/afreon/arti…

单例设计模式共享数据问题分析、解决

一般,我们都是在主线程中(main函数内)创建单例类的对象,这一不会引起任何问题。但是,现在我们面临着另一个问题:需要在自己创建的线程中(非主线程中)来创建单例类的对象(比如上述所说的MyCLS类),这种线程可能不止一个。此时,我们可能面临多个GetInstance()成员函数需要互斥的情况。可以在加锁前判断m_instance是否为空,否则每次调用Singleton::getInstance()都要加锁,十分影响效率。因为每次调用MyCLS::getInstance()都要加锁,十分影响效率。因此,在加锁前再次判断m_instance是否为空(这即为双重锁定/双重检查)。

#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
std::mutex my_mutex;
//单例类例子codes
class MyCLS {
private:
	MyCLS(){}//私有化类的构造函数时,类外部就不可以用className ObjName的方式来创建类的对象了。
private:
	static MyCLS* m_instance;//静态成员变量必须是类内声明,类外初始化
public:
	//首先你得承认一个事实是:
	//如果if (m_instance != nullptr) 条件成立,一定代表m_instance一定被new过了
	//如果if (m_instance == nullptr) 条件成立,并不代表m_instance一定没被new过了
 
	//下面这个创建对象指针的函数getInstance()就算多个线程一起共享的代码数据!
	static MyCLS* getInstance() {
    //因为每次调用MyCLS::getInstance()都要加锁,十分影响效率。
    //因此,在加锁前再次判断m_instance是否为空(这即为双重锁定/双重检查)。
		if (m_instance == nullptr) {//这就叫做是双重检查or双重锁定
			std::lock_guard<std::mutex> sbguard(my_mutex);//自动加锁
			if (m_instance == nullptr) {
				m_instance = new MyCLS();
				static CGarHuishou cl;//静态成员
			}
		}
		return m_instance;
	}
	void func() {
		static int nums = 0;
		nums++;
		cout << "test codes " <<nums<< endl;
	}
 
	class CGarHuishou {//类中嵌套另一个类,这个类专门用于析构单例类中的new的对象所占据的内存空间!
	public:
		~CGarHuishou() {
			if (MyCLS::m_instance) {//非空 再delete
				delete MyCLS::m_instance;
				MyCLS::m_instance = nullptr;
				cout << "~CGarHuishou()执行了!" << endl;
			}
		}
	};
};
//静态成员变量必须是类内声明,类外初始化
MyCLS* MyCLS::m_instance = nullptr;
//线程入口函数
void mythread() {
	cout << "我的线程开始执行了!" << endl;
	MyCLS* p_a = MyCLS::getInstance();//这里很可能就会出问题了!
	cout << "我的线程执行完毕了!" << endl;
	return;
}
int main(void) {
	//创建了2个线程,虽然这2个线程都分别走的是同一条通路,
	//但是,毕竟是2个线程,彼此互不相关
	//这时候问题就来了,当mytobj1这个线程1执行到MyCLS* p_a = MyCLS::getInstance();时
	//刚刚准备调用MyCLS类的getInstance函数中的m_instance = new MyCLS();这行代码时,还没运行呢
	//操作系统就切换到mytobj2这个线程2中去了,比如此时线程2刚好new了MyCLS对象后,操作系统又切换回
	//mytobj1这个线程1中去,那么此时线程1又会new一个MyCLS对象!那么此时就会有2个MyCLS对象的出现
	//这就出现问题了,因为单例类中只允许创建一个对象!
 
    //此时,就可以用双重锁定的way去deal该问题!
	thread mytobj1(mythread);
	thread mytobj2(mythread);
	mytobj1.join();
	mytobj2.join();
	return 0;
}

std::call_once()

std::call_once()函数模板:保证一个函数只被调用一次(C++11引入的函数模板)

格式

std:once_flag flagObjName;
std::call_once(flagObjName,funcName);

std::call_once()保证一个函数只被调用一次的原理:

call_once()需要与一个标记配合使用,这个标记是:std::once_flag(它是一个结构体)。通过std::once_flag这个标记,call_once()就可以决定对应的函数名为funcName的函数是否能执行1次了。当once_flag设置为“未调用”状态时,call_once()很自然地允许别的代码调用该funcName函数一次,然后将once_flag设置为“已调用”状态。那么此后无论有多少次对于该funcName函数的调用,call_once函数模板都不会允许!

解释

之所以能保证该funcName函数只被调用一次。本质上是因为std::call_once这个函数模板具有mutex互斥量的功能。因此可以实现出:当多个线程同时执行时,一个线程会等待另一个线程先执行的效果(和mutex互斥量一样的效果)。

#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
std::mutex my_mutex;
 
std::once_flag  g_flag;//这是一个系统定义的标记
//单例类例子codes
class MyCLS {
public:
	static void CreateInstance() {//只允许该函数被调用一次!s
		if (m_instance == nullptr) {
			m_instance = new MyCLS();
			static CGarHuishou cl;//静态成员
		}
	}
private:
	MyCLS(){}//私有化类的构造函数时,类外部就不可以用className ObjName的方式来创建类的对象了。
private:
	static MyCLS* m_instance;//静态成员变量必须是类内声明,类外初始化
public:
	//下面这个创建对象指针的函数getInstance()就算多个线程一起共享的代码数据!
	static MyCLS* getInstance() {
		//if (m_instance == nullptr) {//这就叫做是双重检查or双重锁定
		//	std::lock_guard<std::mutex> sbguard(my_mutex);//自动加锁
		//	if (m_instance == nullptr) {
		//		m_instance = new MyCLS();
		//		static CGarHuishou cl;//静态成员
		//	}
		//}
 
		std::call_once(g_flag, CreateInstance);
		cout << "call_once执行完毕!" << endl;
		//当2个线程都执行到此处时,其中一个线程要等待另一个线程执行完CreateInstance()函数才能够再次调用call_once函数
		//但是此时g_flag已经被标记为“已调用”状态了,so此时另一个线程就不能再次调用此CreateInstance()函数了!
		//这样就deal 了单例设计模式中写多线程代码时所出现的问题!
		return m_instance;
	}
	void func() {
		static int nums = 0;
		nums++;
		cout << "test codes " <<nums<< endl;
	}
 
	class CGarHuishou {//类中嵌套另一个类,这个类专门用于析构单例类中的new的对象所占据的内存空间!
	public:
		~CGarHuishou() {
			if (MyCLS::m_instance) {//非空 再delete
				delete MyCLS::m_instance;
				MyCLS::m_instance = nullptr;
				cout << "~CGarHuishou()执行了!" << endl;
			}
		}
	};
};
//静态成员变量必须是类内声明,类外初始化
MyCLS* MyCLS::m_instance = nullptr;
 
//线程入口函数
void mythread() {
	cout << "我的线程开始执行了!" << endl;
	MyCLS* p_a = MyCLS::getInstance();//这里很可能就会出问题了!
	cout << "我的线程执行完毕了!" << endl;
	return;
}
int main(void) {
	//创建了2个线程,虽然这2个线程都分别走的是同一条通路,
	//但是,毕竟是2个线程,彼此互不相关
	//这时候问题就来了,当mytobj1这个线程1执行到MyCLS* p_a = MyCLS::getInstance();时
	//刚刚准备调用MyCLS类的getInstance函数中的m_instance = new MyCLS();这行代码时,还没运行呢
	//操作系统就切换到mytobj2这个线程2中去了,比如此时线程2刚好new了MyCLS对象后,操作系统又切换回
	//mytobj1这个线程1中去,那么此时线程1又会new一个MyCLS对象!那么此时就会有2个MyCLS对象的出现
	//这就出现问题了,因为单例类中只允许创建一个对象!
	thread mytobj1(mythread);
	thread mytobj2(mythread);
	mytobj1.join();
	mytobj2.join();
	return 0;
}

第八节:condition_variable、wait、notify_one、notify_all(重要)

条件变量std::condition_variable、wait、notify_one

  • std::condition_variable:实际上是一个类,是一个和条件相关的类,说白了就是等待一个条件达成。(注意:只有unique_lock和condition_variable配合使用才能使用其成员函数!)

  • wait():wait()用来等一个东西。

    • 如果wait()的第2个参数的返回值是true,那么wait()直接返回,并继续执行后续的代码
    • 如果wait()的第2个参数的返回值是false,那么wait()将解锁互斥量,并堵塞到本行(堵塞到啥时候为止呢?堵塞到其他某个线程调用notify_one()这个condition_variable类的成员函数为止)
    • 如果wait()没有第2个参数 ==> my_condition.wait(sbguard);此时就和第2个参数的返回值为false的效果是一样的!wait()将解锁互斥量,并堵塞到本行。堵塞到其他某个线程调用到notify_one()这个condition_variable类的成员函数为止。
  • notify_one():一次只能通知一个的线程,唤醒这一个线程中的condition_variable类的.wait()函数!也即(2个线程中)唤醒另一个线程中的wait()函数。当这个wait恢复后,会做2件事情:

    1. 唤醒后的wait()会不断尝试获取互斥量锁,如果获取不到那么流程就卡在wait()这里继续等待获取,如果获取到了,那么wait()就继续往下执行代码(获取到了锁就表示此时又给该线程上锁了)
    2. 被唤醒后,如果wait有第二个参数就判断第2个参数(谓词)。
      • 如果此时谓词返回值为false,那wait又对互斥量解锁,然后又休眠,等待再次被notify_one()唤醒,再重复尝试拿到互斥锁并判断第2个参数,如此循环反复下去。
      • 如果此时谓词返回值为true,则wait返回,流程可以继续往下执行了(此时互斥量还是已被锁住)。
    3. 如果wait没有第二个参数,则wait返回,流程走下去(此时互斥量还是已被锁住)。

注意: 流程只要走到了wait()的下面则互斥量一定是被锁住了的。

#include<iostream>
#include<thread>
#include<list>
#include<mutex>
#include<condition_variable>
using namespace std;
class A {
private:
	list<int> msgRecvQueue;//处理命令消息的容器
	mutex my_mutex;//创建一个互斥量!
	//mutex my_mutex2;//创建一个互斥量!
	std::condition_variable my_condition;//创建一个条件变量类 的 对象
public:
	//把收到的消息(玩家命令)插入到消息容器中的线程函数
	void inMsgRecvQueue() {
		
		for (int i = 0; i < 10000; i++) {
			cout << "inMsgRecvQueue()执行,插入一个元素: " << i << endl;
			std::unique_lock<std::mutex> sbguard1(my_mutex);
			msgRecvQueue.push_back(i);//假设这个数字i就是我收到的命令
			my_condition.notify_one();
            //这行代码执行完毕后, outMsgRecvQueue()中的wait()函数就会给唤醒!
		}
		return;
	}
	//把数据从消息容器中取出的线程函数
	void outMsgRecvQueue() {
		int command = 0;
		while (true) {
 
			//wait()函数是用来等 待一个东西的
			//如果第2个参数(谓词)返回值为false时,那么wait()将解锁互斥量mutex,并堵塞到本行
			//那堵塞到啥时候为止呢?堵塞到其他某个线程调用std::condition_variable类对象的.notify_one()成员函数为止;
			
			/*
			wait()用来等一个东西 
			如果wait()的第2个参数的返回值是true,那么wait()直接返回,并继续执行后续的代码
			如果wait()的第2个参数的返回值是false,那么wait()将解锁互斥量,并堵塞到本行
				堵塞到啥时候为止呢?堵塞到其他某个线程调用.notify_one()这个condition_variable类的成员函数为止
			如果wait()没有第2个参数 ==> my_condition.wait(sbguard);
			此时就和第2个参数的返回值为false的效果是一样的!
			wait()将解锁互斥量,并堵塞到本行。堵塞到其他某个线程调用.notify_one()这个condition_variable类的成员函数为止
 			*/
			std::unique_lock<std::mutex> sbguard(my_mutex);
			my_condition.wait(sbguard, [this](void) {
				if (!this->msgRecvQueue.empty())return true;
				return false;
				});
 
				command = msgRecvQueue.front();//返回第一个元素,但是不检查元素是否存在
				msgRecvQueue.pop_front();//移除消息容器中的首元素
			//my_condition.notify_one
			sbguard.unlock();//这是因为unique_lock的灵活性,so我们可以随时地unlock解锁,以免锁住太长时间!
			cout << "outMsgRecvQueue()执行,取出一个元素 " << command << endl;
		}
	}
};
int main(void) {
	A mytobj;
	thread Inthread(&A::inMsgRecvQueue, &mytobj);//&mytobj也可以写为std::ref(mytobj)
	//也只有这样才能够传真正的引用进去到线程函数中!
	thread Outthread(&A::outMsgRecvQueue, &mytobj);
	Inthread.join();
	Outthread.join();
	cout << "主线程执行完毕,进程准备退出!" << endl;
	return 0;
}

对上述代码之深入思考

上面的代码可能导致出现一种情况:因为outMsgRecvQueue()与inMsgRecvQueue()并不是一对一执行的,所以当程序循环执行很多次以后,在msgRecvQueue 中可能已经有了很多命令消息了。但是,outMsgRecvQueue还是被唤醒一次只处理一条数据,这时命令消息多到你的代码处理不过来了。可以考虑把outMsgRecvQueue多执行几次(用循环),或者对inMsgRecvQueue进行限流。以达到优化这个多线程代码的目

notify_all

notify_all(): 一次能通知all(2个及以上)的线程中的condition_variable类的wait()函数,并唤醒他们的wait()函数(唤醒后wait就会判断其第2个参数是否返回true,是的话就给当前这个线程上锁并继续往下执行,直到unlock;若为false,则继续释放锁,等待下一次唤醒了再重新判断!如此循环反复下去...)

这一小节的知识点,如果觉得自己用不好的话,可以选择不用,换而使用别的更加稳定的普通写法也ok,因为写多线程的代码最重要的一个要求就是你的代码必须保持稳定

第九节:async、future、packaged_task、promise

std::async、std::future创建后台任务并返回值

std::async(async中文意思是异步的)是一个函数模板

std::async作用:启动一个异步任务,当把一个异步任务启动起来之后,它就会返回一个std::future对象!(std::future是一个类模板)(人话:开启一个线程,并用该线程的返回值创建一个future对象并返回)

格式

std::future<threadFuncReturnVarType> futureObjName = std::async(线程入口函数名);
//std::async这个模板函数会执行对应的线程入口函数并且
//std::async这个模板函数还会返回一个future对象
//这个返回的std::future还会带着async函数执行的线程入口函数的返回值!

解释:

什么叫做是启动一个异步任务:自动创建一个线程,并执行对应的线程入口函数,它会返回一个std::future模板类的对象。这个std::future对象就包含有线程入口函数所返回的结果。(也即是该线程所返回的结果)当然,我们可以通过调用该类模板对象的成员函数get()来查看该结果。

future:将来的意思,有人也称呼std::future提供了一种访问异步操作结果的机制。也就是说这个结果你没有办法马上拿到。但在不久的将来,也即线程执行完毕时,你就能够拿到结果了。所以我们可以这样理解:这个future对象里会保存一个返回值,这个返回值在未来的某个时刻你就能够通过get()成员函数拿到。

注意①:在使用std::async、std::future之前,必须包含头文件future,即:

#include<future>

注意②:future类对象的 get() 成员函数一定是要等到某个线程函数执行完毕并收到(取到)该线程的返回值后,才继续往下执行的。(且get()函数只能执行1次,执行2次及以上就会报异常!)

#include<iostream>
#include<thread>
#include<mutex>
#include<future>
#include<chrono>
using namespace std;
//线程的入口函数,其返回值为5!
int mythreadRukou() {
	cout << "mythread() start " << "threadid = " << std::this_thread::get_id() << endl;
	std::chrono::milliseconds dura(2000);//设置休息时间为2秒钟!因为 1 s == 1000 ms 
	std::this_thread::sleep_for(dura);//休息了一定的时长
	cout << "mythread() end " << "threadid = " << std::this_thread::get_id() << endl;
	return 5;
}//打印新的线程id
int main(void) {
	//《1》std::async、std::future创建后台任务并 返回值
	//以往我们都只是用thread类创建线程,然后用》join()方法来阻塞主线程,当子线程返回后
	//即可与主线程汇合 
	//现在,我们有这样一个需求,即:让线程作返 回值!   
 
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	std::future<int> result = std::async(mythreadRukou);//async函数模板会自动帮助我们
	//执行线程入口函数并返回一个std::furture对象!!!(注意:流程并不会卡在这儿)
 
	result.wait();//这个wait函数仅会等待线程返回而已,本身并不返回任何的结果!
	auto res = result.get();
	//auto res2 = result.get();//错误!因为future对象的.get()成员函数不能调用多次!只能调用1次而已!
	//调用.get()2次及以上就会报异常!!!
   	cout << "threadfunc result variable is " << res << endl;
	//这行代码会让程序卡在这里,直到拿到线程函数的返回值为止,才往下继续执行!
	//若一直拿不到这个线程函数的返回值的话,.get()函数就会一直卡在这儿了!
	return 0;
}                
#include<iostream>
#include<thread>
#include<mutex>
#include<future>
#include<chrono>
using namespace std;
//类的成员函数作为线程的入口函数,其返回值为888!
class A {
public:
	int AthreadRukou(int var) {
		cout << "参数car = " << var << endl;
		cout << "Athread() start " << "threadid = " << std::this_thread::get_id() << endl;
		std::chrono::milliseconds dura(2000);//设置休息时间为2秒钟!因为 1 s == 1000 ms 
		std::this_thread::sleep_for(dura);//休息了一定的时长
		cout << "Athread() end " << "threadid = " << std::this_thread::get_id() << endl;
		return 888;
	}
};
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	A a;
	int var = 118;
	std::future<int> result = std::async(&A::AthreadRukou,std::ref(a),var);
	//这里第1个参数是线程入口函数地址,然后第2个参数是A类对象的引用(也可以写&a),第3个参数才是线程入口函数的形参
	//注意:这里必须要用std::ref(a) or &a 来写!这样写你的线程代码才是安全的!
	result.wait();//这个wait函数仅会等待线程返回而已,本身并不返回任何的结果!
	auto res = result.get();
   	cout << "threadfunc result variable is " << res << endl;
	cout << "main thread end!" << endl;
	return 0;
}

补充知识: 我们还可以通过向std::async()函数传递一个参数,该参数为std::launch类型(枚举类型),来达到一些特殊的目的!(std::launch::deferred 和 std::launch::async

std::launch::deferred

(defer推迟、延迟的意思)表示:线程入口函数的调用会被延迟,一直到std::future的wait()或者get()函数被调用时(由主线程调用)才会执行该线程入口函数。

注意

  1. 这里使用了std::launch::deferred参数后,使得实际上并没有创建新的子线程,而是直接在主线程中完成了子线程的工作!(这确实有点奇怪)若wait()或者get()根本没有被调用,则线程入口函数就不会被执行了!
#include<iostream>
#include<thread>
#include<mutex>
#include<future>
#include<chrono>
using namespace std;
class A {
public:
	int AthreadRukou(int var) {
		cout << "参数car = " << var << endl;
		cout << "Athread() start " << "threadid = " << std::this_thread::get_id() << endl;
		std::chrono::milliseconds dura(2000);//设置休息时间为2秒钟!因为 1 s == 1000 ms 
		std::this_thread::sleep_for(dura);//休息了一定的时长
		cout << "Athread() end " << "threadid = " << std::this_thread::get_id() << endl;
		return 888;
	}
};
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	A a;
	int var = 118;
	std::future<int> result = std::async(std::launch::deferred, &A::AthreadRukou,std::ref(a),var);
	//result.wait();
	auto res = result.get();
   	cout << "threadfunc result variable is " << res << endl;
	cout << "main thread end!" << endl;
	return 0;
}

运行结果:

可以看到,现在程序执行的代码都是从主线程中去执行的,因为每个线程的线程id都是唯一的!

  1. 若wait()或者get()根本没有被调用,则线程入口函数就不会被执行了!
#include<iostream>
#include<thread>
#include<mutex>
#include<future>
#include<chrono>
using namespace std;
class A {
public:
	int AthreadRukou(int var) {
		cout << "参数car = " << var << endl;
		cout << "Athread() start " << "threadid = " << std::this_thread::get_id() << endl;
		std::chrono::milliseconds dura(2000);//设置休息时间为2秒钟!因为 1 s == 1000 ms 
		std::this_thread::sleep_for(dura);//休息了一定的时长
		cout << "Athread() end " << "threadid = " << std::this_thread::get_id() << endl;
		return 888;
	}
};
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	A a;
	int var = 118;
	std::future<int> result = std::async(std::launch::deferred, &A::AthreadRukou,std::ref(a),var);
	//result.wait();
	//auto res = result.get();
   	//cout << "threadfunc result variable is " << res << endl;
	cout << "main thread end!" << endl;
	return 0;
}

运行结果:

可见,若wait()或者get()根本没有被调用,则根本就不会调用到子线程的入口函数了!

std::launch::async

作用: 加在std::async这个函数模板中,让std::future类对象调用std::async函数并绑定到某一个线程入口函数时,就马上立刻创建新的子线程,并开始执行线程入口函数!

注意: 默认情况下,若std::async函数模板你不加额外的参数,则是以std::launch::async | std::launch::deferred这个参数为默认值的。

#include<iostream>
#include<thread>
#include<mutex>
#include<future>
#include<chrono>
using namespace std;
class A {
public:
	int AthreadRukou(int var) {
		cout << "参数car = " << var << endl;
		cout << "Athread() start " << "threadid = " << std::this_thread::get_id() << endl;
		std::chrono::milliseconds dura(2000);//设置休息时间为2秒钟!因为 1 s == 1000 ms 
		std::this_thread::sleep_for(dura);//休息了一定的时长
		cout << "Athread() end " << "threadid = " << std::this_thread::get_id() << endl;
		return 888;
	}
};
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	A a;
	int var = 118;
	/*std::future<int> result = std::async(std::launch::deferred, &A::AthreadRukou,std::ref(a),var);*/
	std::future<int> result = std::async(std::launch::async, &A::AthreadRukou, std::ref(a), var);
	//result.wait();
	auto res = result.get();
   	cout << "threadfunc result variable is " << res << endl;
	cout << "main thread end!" << endl;
	return 0;
}

运行结果:

这说明,std::launch::async这参数使得std::async这个函数不需要等待future类对象的get()/wait()成员函数的执行才开始执行对应绑定了的线程入口函数,也即加入这个参数给std::async函数后,可以直接开始创建新的子线程并且开始执行该子线程入口函数!

std::packaged_task

std::packaged_task:是一个类模板。它的模板参数是线程入口函数的返回值类型+(形参表)

使用格式:

std::packaged_task<线程入口函数的返回值+(参数表)> objName(指向线程入口函数的可调用对象)
//比如:
std::packaged_task <int(int)> mypkt(mythreadRukou);
//packaged_task对象指向一个返回值为int,参数表为(int)的线程入口函数

作用解释:通过std::packaged_task把各种可调用对象函数(函数指针、Lambda函数、函数符)包装起来,以便于将其作为线程入口函数来被调用!

用函数名作为可调用对象

#include<iostream>
#include<thread>
#include<mutex>
#include<future>
#include<chrono>
using namespace std;
//线程的入口函数,其返回值为18!
int mythreadRukou(int var) {
	cout << "mythread() start " << "threadid = " << std::this_thread::get_id() << endl;
 	std::chrono::milliseconds dura(2000);//设置休息时间为2秒钟!因为 1 s == 1000 ms 
	std::this_thread::sleep_for(dura);//休息了一定的时长
	cout << "mythread() end " << "threadid = " << std::this_thread::get_id() << endl;
	return 18;
}
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	std::packaged_task <int(int)> mypkt(mythreadRukou);//把线程入口函数mythreadRukou通过packaged_task包装起来!
	std::thread thread1(std::ref(mypkt), 1);//线程直接开始执行 第2个参数是传的参数给线程入口函数的!
	thread1.join();
	std::future<int> futureObj = mypkt.get_future();
	//std::future<T>对象里保存有对应的线程入口函数的返回值,这里也即futureObj保存了线程入口函数的返回值
	auto res = futureObj.get();
	cout << res << endl;
	cout << "main thread end!" << endl;
	return 0;
}

运行结果:

用Lambda函数作为可调用对象

#include<iostream>
#include<thread>
#include<mutex>
#include<future>
#include<chrono>
using namespace std;
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	std::packaged_task<int(int)> mptk([](int tvar) {
		cout << "mythread() start " << "threadid = " << std::this_thread::get_id() << endl;
		std::chrono::milliseconds dura(2000);//设置休息时间为2秒钟!因为 1 s == 1000 ms 
		std::this_thread::sleep_for(dura);//休息了一定的时长
		cout << "mythread() end " << "threadid = " << std::this_thread::get_id() << endl;
		return 28;
	});
	std::thread thread2(std::ref(mptk), 0);
	thread2.join();
	std::future<int> futureObj = mptk.get_future();
	auto res = futureObj.get();
	cout << res << endl;
	cout << "main thread end!" << endl;
	return 0;
}

运行结果:

#include<iostream>
#include<thread>
#include<mutex>
#include<future>
#include<chrono>
using namespace std;
//线程的入口函数,其返回值为18!
int mythreadRukou(int var) {
	cout << "mythread() start " << "threadid = " << std::this_thread::get_id() << endl;
 	std::chrono::milliseconds dura(2000);//设置休息时间为2秒钟!因为 1 s == 1000 ms 
	std::this_thread::sleep_for(dura);//休息了一定的时长
	cout << "mythread() end " << "threadid = " << std::this_thread::get_id() << endl;
	return 18;
}
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	std::packaged_task<int(int)> mptk(mythreadRukou);
	mptk(2);
    //因为packaged_task包装了可调用对象,因此packaged_task对象也是一个可调用对象
    //但是如果直接用packaged_task对象来调用线程入口函数的话,则实际上并不会产生新的子线程
    //而是像在主线程调用一个函数一样去执行!
	std::future<int> obj = mptk.get_future();
	auto res = obj.get();
	cout << res << endl;
	cout << "main thread end!" << endl;
	return 0;
}

运行结果:

你甚至可以结合容器来使用std::packaged_task对象

#include<iostream>
#include<thread>
#include<mutex>
#include<future>
#include<chrono>
#include<vector>
using namespace std;
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	vector< std::packaged_task<int(int)> > myThreadTasks;
	std::packaged_task<int(int)> mptk([](int) {
		cout << "mythread() start " << "threadid = " << std::this_thread::get_id() << endl;
		std::chrono::milliseconds dura(2000);//设置休息时间为2秒钟!因为 1 s == 1000 ms 
		std::this_thread::sleep_for(dura);//休息了一定的时长
		cout << "mythread() end " << "threadid = " << std::this_thread::get_id() << endl;
		return 18;
	});
	myThreadTasks.push_back(std::move(mptk));//移动语义,使得mptk为空,其原来所指向的内存空间的访问权限给到myThreadTasks容器中的新对象了!
	std::packaged_task<int(int)> mptk2;
	auto iter = myThreadTasks.begin();
	mptk2 = std::move(*iter);//移动语义,使得myThreadTasks容器中的std::packaged_task<int(int)>对象为空,其原来所指向的内存空间的访问权限给到了mptk2!
	myThreadTasks.erase(iter);
	mptk2(123);                 
	std::future<int> obj = mptk2.get_future();//与future配合使用时,要用future对象的.get_future()成员函数
	auto res = obj.get();
	cout << res << endl;
	cout << "main thread end!" << endl;
	return 0;
}

运行结果:

当然,给出这么多demo代码只是让你知道如何去使用std::packaged_task对线程入口函数进行封装而已,不是说非要在实战中去使用!(实战中你自己熟悉哪一些知识点就用哪一些知识点来写代码即可,首先保证你写的代码是持续稳定的!)

std::promise

std::promise:是个类模板,我们可以在某个线程中给这个类模拟对象赋值,然后再在别的某个线程中把这个值取出来。

使用格式

std::promise<要保存到值得类型> promiseObjName;
 
//比如:
std::promise<int> pObj;
//声明了一个promise类对象,这个名为pObj的对象所保存的值为int型的!
//这个值是从线程入口函数中返回给这个对象的!
#include<iostream>
#include<thread>
#include<mutex>
#include<future>
#include<chrono>
using namespace std;
void mythreadfunc(std::promise<int> &tmp,int calc) {
	cout << "mythreadfunc() start " << "threadid = " << std::this_thread::get_id() << endl;
	//在这里线程入口函数中do一系列复杂的运算
	calc++;
	calc *= 10;
	//做其他运算,比如整整话费了5s钟
	std::chrono::milliseconds dura(5000);//定义休息的时间为5s
	std::this_thread::sleep_for(dura);//休息5s这个动作
	
	//终于计算出结果了
	int res = calc;
	tmp.set_value(res);//将结果保存到std::promise<int>对象的.set_value()函数中去
	cout << "mythreadfunc() end " << "threadid = " << std::this_thread::get_id() << endl;
	return;
}
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	std::promise<int> prom;
	std::thread thd1(&mythreadfunc, std::ref(prom), 180);
	thd1.join();
	//获取结果值
	std::future<int> fobj = prom.get_future();
	auto res = fobj.get();//因为上述thd1.join()时已经执行完子线程函数来,因此get函数不用等待它执行完毕了,直接拿到返回值!
	cout << res << endl;
	cout << "main thread end!" << endl;
	return 0;
} 

运行结果:

#include<iostream>
#include<thread>
#include<mutex>
#include<future>
#include<chrono>
using namespace std;
//第一个线程
void mythreadfunc(std::promise<int> &tmp,int calc) {
	cout << "mythreadfunc() start " << "threadid = " << std::this_thread::get_id() << endl;
	//在这里线程入口函数中do一系列复杂的运算
	calc++;
	calc *= 10;
	//做其他运算,比如整整话费了5s钟
	std::chrono::milliseconds dura(5000);//定义休息的时间为5s
	std::this_thread::sleep_for(dura);//休息5s这个动作
	
	//终于计算出结果了
	int res = calc;
	tmp.set_value(res);//将结果保存到std::promise<int>对象的.set_value()函数中去
	cout << "mythreadfunc() end " << "threadid = " << std::this_thread::get_id() << endl;
	return;
	
}
//另外一个线程(第2个线程)
void mythreadfunc2(std::future<int> &tmpf) {
	//把第1个线程返回的结果让第2个线程拿来使用!
	auto res = tmpf.get();
	cout << "mythreadfunc2中的 res = " << res << endl;
	return;
}
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	std::promise<int> prom;//声明了一个名为prom的promise对象,它保存的值为int型
        //这个值是从线程入口函数中返回给这个对象的!
	std::thread thd1(&mythreadfunc, std::ref(prom), 180);
	thd1.join();
	//获取结果值
	std::future<int> fobj = prom.get_future();
	//auto res = fobj.get();//因为上述thd1.join()时已经执行完子线程函数来,因此get函数不用等待它执行完毕了,直接拿到返回值!
	//cout << res << endl;//注意:get函数只可以调用1次!
	std::thread thd2(&mythreadfunc2, std::ref(fobj));
	thd2.join();
	cout << "main thread end!" << endl;
	return 0;
}

运行结果:

小结

问: 我们学这么多的多线程函数和类,到底怎么用?什么时候用呢?

答: 我们学习这些东西的目的,其实并不是要把他们都用在实际的开发中去。相反,如果我们能够用最少的代码写出一个稳定的、高效的多线程程序,则这更值得赞赏。我们为了成长,必须要阅读一些高手写的代码,从而快速实现自己代码的基类,提升自己的coding技术。记住,学这些多线程知识,更多的是为我们将来能够读懂高手甚至大师写的代码而铺路!

第十节:future的其他成员函数、shared_future、atomic

std::future的其他成员函数

std::future的get()成员函数:可以获取对应绑定到std::future身上的线程的入口函数的返回值,且get()函数只能调用一次。

#include<iostream>
#include<thread>
#include<chrono>
#include<future>
using namespace std;
int mythread() {
	cout << "mythread() start " << " threadid = " << std::this_thread::get_id() << endl;//新的线程id
	std::chrono::milliseconds dura(5000);//定义休息的时间为5s
	std::this_thread::sleep_for(dura);//休息一定时长
	cout << "mythread() end " << " threadid = " << std::this_thread::get_id() << endl;//新的线程id
	return 5;
}
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	std::future<int> result = std::async(mythread);//async
	cout << "continue ..." << endl;
	auto res = result.get();//get函数获取线程函数返回值
	cout << "res = " << res << endl;
	cout<<"main end!"<<endl;
	return 0;
}

std::future的wait_for()成员函数:会等待一定的时间,并返回一个std::future_status的枚举类型。

enum class future_status { // names for timed wait function returns
    ready,
    timeout,
    deferred
};//该枚举类型有3种状态,分别是ready、timeout、deferred

由于ready和timeout状态很简单,这里就不给出其对应的test-codes了。这里只给出我测试deferred状态的代码!我的注释也要看,这很重要

#include<iostream>
#include<thread>
#include<chrono>
#include<future>
using namespace std;
int mythread() {
	cout << "mythread() start " << " threadid = " << std::this_thread::get_id() << endl;//新的线程id
	std::chrono::milliseconds dura(5000);//定义休息的时间为5s
	std::this_thread::sleep_for(dura);//休息一定时长
	cout << "mythread() end " << " threadid = " << std::this_thread::get_id() << endl;//新的线程id
	return 5;
}
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	std::future<int> result = std::async(std::launch::deferred,mythread);//async
	cout << "continue ..." << endl;
	//枚举类型
	std::future_status status = result.wait_for(std::chrono::seconds(6));//等待1s钟!
	if (status == std::future_status::timeout) {
		//当future对象result 等待对应绑定到它身上的线程入口函数等待了6s钟后,若线程入口函数仍然未执行完毕的话
		//则.wait_for函数会返回一个timeout的状态!
		cout << "子线程运行还没结束呢!超时啦!" << endl;
	}
	else if (status == std::future_status::ready) {
		//当future对象result 等待对应绑定到它身上的线程入口函数等待了6s钟后,若线程入口函数已经执行完毕的话
		//则.wait_for函数会返回一个ready的状态!
		cout << "子线程运行已经结束了!" << endl;
		auto res = result.get();
		cout << "res = " << res << endl;
	}
	else if (status == std::future_status::deferred) {
		//当std::async函数模板的第一个参数标记为std::launch::deferred时,会返回该std::future_status::deferred枚举类型
        //也即std::async函数模板的第一个参数标记为std::launch::deferred时本条件成立!
		//且,上一节课我们学了,当async函数的第一个参数为launch::deferred时,会延迟对应绑定的线程入口函数的执行
		//且,系统将一直延迟这子线程入口函数的执行,当后续代码中future对象没有用.wait()或者.get()函数时,此时就不会再执行该子线程入口函数了!
		//则.wait_for函数会返回一个deferred的状态!
		cout << "子线程入口函数根本就没有执行!" << endl;//或者说该子线程函数被延迟执行!
	}
	cout<<"main end!"<<endl;
	return 0;
}

运行结果:

即便你把上述的std::future_status::deferred的条件语句改成如下:

else if (status == std::future_status::deferred) {
    auto res = result.get();
    cout << "res = " << res << endl;
    cout << "子线程入口函数根本就没有执行!" << endl;
}

也不能够创建新的子线程,而仅仅是在主线程去调用该线程入口函数罢了~(下图可验证我说的这一点) 再次运行的结果:

都是同一个线程id,说明都是主线程来执行这段代码的,而没有创建新的子线程来做

std::shared_future

问题:前面所说的std::future对象能拿到线程入口函数执行完毕之后的返回值,但是,该对象要获取该返回值还需要使用成员函数.get(),且只能用一次!那么如果说当有多个线程都需要用到该返回值时,这就行不通了吧?是的!

回答:因此,就引入std::shared_future函数!

std::shared_future:和std::future类模板的对象类似,都可以拿到线程入口函数的返回值!

格式

std::shared_future<线程入口函数返回值的类型> sharedfutureObjName;

std::future和std::shared_future的主要区别: std::future的get函数是移动(move)数据(这样就使得只有另外1个线程可以使用这个返回值数据了)因此,future的get函数只能使用1次。std::shared_future的get函数是复制(copy)数据(这样就使得多个线程都可以使用这个返回值数据了)。因此,shared_future的get函数能使用多次。

#include<iostream>
#include<thread>
#include<chrono>
#include<future>
using namespace std;
int mythread(int  val) {
	cout << "mythread() start " << "threadid = " << std::this_thread::get_id() << endl;//新的线程id
	std::chrono::milliseconds dura(5000);//定义休息的时间为5s
	std::this_thread::sleep_for(dura);//休息一定时长
	cout << "mythread() end " << " threadid = " << std::this_thread::get_id() << endl;//新的线程id
	return 5;
}
void mythread2(std::shared_future<int>& tmf) {
	cout << "mythread2() start " << "thread id = " << std::this_thread::get_id() << endl;//线程id
	auto res = tmf.get();//获取线程返回值,注意,任何时,只能get一次,否则会报异常!
	auto res2 = tmf.get();
	cout << "res1 = " << res << ",res2 = " << res2 << endl;
	cout << "mythread2() end " << " threadid = " << std::this_thread::get_id() << endl;//线程id
	return;
}
int main(void) {
	//2-std::shared_future
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	std::packaged_task<int(int)> mypt(mythread);//我们把mythread这个线程函数通过packaged_task包装起来
	std::thread t1(std::ref(mypt), 1);//线程直接开始执行,第二个参数为线程入口函数的参数
	t1.join();
	//调用join函数让主线程等待子线程执行完毕,再和主线程回合一起往下执行!
	std::future<int> res = mypt.get_future();//packaged_task对象里面用get_future就可以传给future对象
	//并让res这个future对象拿到线程1结束后的返回值
	//bool ifchanget = res.valid();
	
	std::shared_future<int> res_s(std::move(res));//这行代码执行完毕之后,res_s有值了!但是res为空了!且 std::move(res) ==> res.share()
	//std::shared_future<int> res_s(res.share());//这行代码执行完毕之后,res_s有值了!但是res为空了!
	//ifchanget = res.valid();
	auto threadretres1 = res_s.get();
	auto threadretres2 = res_s.get();
	auto threadretres3 = res_s.get();
	//std::thread t2(mythread2, std::ref(res));//第2个参数为线程入口函数2的参数
	std::thread t2(mythread2, std::ref(res_s));//第2个参数为线程入口函数2的参数
	t2.join();
	cout << "main end!" << std::this_thread::get_id() << endl;
	return 0;
}

运行结果:

#include<iostream>
#include<thread>
#include<chrono>
#include<future>
using namespace std;
int mythread(int  val) {
	cout << "mythread() start " << "threadid = " << std::this_thread::get_id() << endl;//新的线程id
	std::chrono::milliseconds dura(5000);//定义休息的时间为5s
	std::this_thread::sleep_for(dura);//休息一定时长
	cout << "mythread() end " << " threadid = " << std::this_thread::get_id() << endl;//新的线程id
	return 5;
}
void mythread2(std::shared_future<int>& tmf) {
	cout << "mythread2() start " << "thread id = " << std::this_thread::get_id() << endl;//线程id
	auto res = tmf.get();//获取线程返回值,注意,任何时,只能get一次,否则会报异常!
	auto res2 = tmf.get();
	cout << "res1 = " << res << ",res2 = " << res2 << endl;
	cout << "mythread2() end " << " threadid = " << std::this_thread::get_id() << endl;//线程id
	return;
}
int main(void) {
	//2-std::shared_future
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	std::packaged_task<int(int)> mypt(mythread);//我们把mythread这个线程函数通过packaged_task包装起来
	std::thread t1(std::ref(mypt), 1);//线程直接开始执行,第二个参数为线程入口函数的参数
	t1.join();
	std::shared_future<int> res_s(mypt.get_future());
	//通过packaged_task对象中的.get_future()函数的返回值std::future对象用于构造一个shared_future对象!(这里涉及到了隐式类型转换!)
 
	std::thread t2(mythread2, std::ref(res_s));//第2个参数为线程入口函数2的参数
	t2.join();
	cout << "main end!" << std::this_thread::get_id() << endl;
	return 0;
}

运行结果:

原子操作std::atomic

在C++11中,引入了std::atomic这个类模板来进行原子操作。(std::atomic就是用来封装这个变量类型的值的。)

格式

std::atomic<要封装的变量的类型> atomicObj;//or atomicObj = 初始值;也ok

原子操作概念引出范例

互斥量:在多线程编程中,是用来保护共享数据的!(这非常重要)

(人话:当某个线程使用or操作共享数据时,就用mutex互斥量这把锁头锁住,让其顺利地执行完毕而不是让操作系统给你切到别的线程去。当操作完成该段共享数据的代码时,锁头就打开,再让别的需要使用该共享数据代码的线程去用!你用完我再用,一个一个排着队!井然有序!简言之:本线程:锁住 操作共享数据 开锁;其他要使用该共享数据的线程:锁住 操作共享数据 开锁,本线程没开锁前,别的要用共享数据的线程就得在这儿给我等着,等我解锁了再说!)

我们除了可以使用互斥量来避免多个线程在操作同一份共享数据时产生的错误!其实,我们还可以使用原子操作来避免这类错误!

原子操作: 是在多线程中不会被打断的程序执行某个代码行。也指的是不可分割的操作,即:这种操作的状态要么是已完成,要么是未完成,不可能出现半完成状态。我们可以把原子操作理解成一种:不需要用到互斥量加锁技术的多线程并发编程方式!(是一种无锁的多线程并发编程方式)也正是因为无锁,所以在保护共享数据代码时,原子操作比互斥量(mutex锁)在效率上要更胜一筹!(CPU遇到原子变量时,就不能切换到别的线程去,只能乖乖等待我这个原子操作执行完毕才能再变回以前按照一定机制切换执行各个线程的模式去,这是操作系统相关的知识了。)

注意互斥量原子操作保护共享数据的代码的效果是一致的!但是,互斥量和原子操作各有各的适用范围:

  • 互斥量的加锁:一般是针对一个代码段(多行代码)
  • 原子操作的加锁:一般是针对某一个对象(变量)(一行代码)(只能应付多线程中对于单个变量的读和写的变化的保护)

因此,当你想保护某个共享数据的对象时,用原子操作较好,想保护某段共享数据代码时,用互斥量加锁解锁的方式较好!

互斥量保护共享数据的代码:

#include<iostream>
#include<thread>
#include<mutex>
using namespace std;
int g_value = 0;
std::mutex my_g_mutex;
//写值线程入口函数
void mythread() {
	for (int i = 0; i < 1000000; i++) {
		//std::unique_lock<std::mutex> unilockObj(my_g_mutex);
        //g_value++;		
//这个unique_lock对象就保证我们一定能够让每次线程进入到for循环时都能执行完g_value++; 这一行代码的操作
		//这样就不会因为操作系统的调度切换导致g_value这个变量没有++成功这种情况的发生!!!
		// or 
		my_g_mutex.lock();
		g_value++;
		my_g_mutex.unlock();
	}
	return;
}
int main(void) {
    //3-原子操作:std::atomic
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	//当有2个线程,一个对变量进行读取值的操作,另一个线程也对这个变量中进行读取值的操作
	//或者2个线程同时对一个变量进行写的操作时,都会产生共享数据时线程之间因操作系统的调度机制导致
    //所操作的共享数据出错的可能!
	std::thread thd1(mythread);
	std::thread thd2(mythread);
	thd1.join();
	thd2.join();
	//创建2个线程同时对于全局变量g_value进行写的操作!
	cout << "2个线程都执行完毕了!现在的 g_value = " << g_value << endl;
	cout << "main end!" << std::this_thread::get_id() << endl;
	return 0;
}

此时,无论运行多少次,结果都是g_value  == 200w:

若不用mutex互斥量or原子操作的话,一定是会在某次结果上出错的!也即g_value的值不总会是200w了的意思!

基本的std::atomic用法范例

原子操作来保护共享数据的代码:

#include<iostream>
#include<thread>
#include<mutex>
#include<atomic>
using namespace std;
//int g_value = 0;
std::atomic<int> g_value = 0;//定义了一个具备原子操作的整型对象g_value
//这个g_value就可以当做是一个int型变量一样去操作!
//写值线程入口函数B
void mythread() {
	for (int i = 0; i < 100000000; i++) {
		g_value++;
		//此时,因为g_value已经是一个原子类型了,因此它对应的操作就算原子操作了(即不会因为被操作系统的调度机制切换线程而打断,可以正常执行下去)!
	}
	return;
}
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	std::thread thd1(mythread);
	std::thread thd2(mythread);
	thd1.join();
	thd2.join();
	//创建2个线程同时对于全局变量g_value进行写的操作!
	//基本的std::atomic用法范例!
	cout << "2个线程都执行完毕了!现在的 g_value = " << g_value << endl;
	cout << "main end!" << std::this_thread::get_id() << endl;
	return 0;
}

运行结果:

#include<iostream>
#include<thread>
#include<chrono>
#include<mutex>
#include<atomic>
using namespace std;
std::atomic<bool> g_ifend = false;//线程退出标记!这里是原子操作!防止在多线程操作该对象时,造成的数据乱套问题!
void mythread() {
	std::chrono::seconds dura(1);//定义一个1s钟的对象
	while (g_ifend == false) {
		//此时系统没要求线程退出,所有本线程可以干自己想干的事儿!
		cout << "thread id = " << std::this_thread::get_id() << " 运行中..." << endl;
		std::this_thread::sleep_for(dura);//休息1s钟!
	}
	cout << "thread id = " << std::this_thread::get_id() << " 运行结束!" << endl;
	return;
}
int main(void) {
	cout << "main threadid = " << std::this_thread::get_id() << endl;
	std::thread thd1(mythread);
	std::thread thd2(mythread);
	//定义这2个子线程的同时,他们就会开始执行!
	//然后让主线程休息5s钟!
	std:chrono::seconds dura(5);
	std::this_thread::sleep_for(dura);
	g_ifend = true;//对原子对象进行写操作,进而让子线程自动结束运行!
	thd1.join();//让thd1子线程与主线程汇合!
	thd2.join();//让thd1子线程与主线程汇合!
	//基本的std::atomic用法范例!
	//cout << "2个线程都执行完毕了!现在的 g_value = " << g_value << endl;
	cout << "main end!" << std::this_thread::get_id() << endl;
	return 0;
}

运行结果:

image.png

虽然std::atomic这个进行原子操作的类模板还有许多的成员函数,但是很多成员函数基本很少用。

第十一节:std::atomic续谈、std::async深入谈

原子操作std::atomic续谈

std::atomic对于需要保护的共享数据所进行的原子操作并不支持所有运算符号,比如:+ 号 std::atomic只支持++、--、+=、-=、|= 等运算符,其他运算符不支持!

demo1:

#include<iostream>
#include<thread>
#include<atomic>
#include<chrono>
using namespace std;
std::atomic<int> g_cnt = 0;
void mythread() {
	cout << "thread id = " << std::this_thread::get_id() << endl;
	for (int i = 0; i < 1000000; i++) {
		g_cnt = g_cnt + 1;
	}
	return;
}
int main(void) {
	cout << "main start ! and main thread id = " << std::this_thread::get_id() << endl;
	std::thread thd1(mythread);
	std::thread thd2(mythread);
	thd1.join();
	thd2.join();
	cout << "g_cnt = " << g_cnt << endl;
	cout << "main thread end! and main thread id = " << std::this_thread::get_id() << endl;
	return 0;
}

运行结果:

image.png

从运行结果可见,g_cnt的计算结果是乱套了的,这正是因为原子操作并不支持所有的运算符而导致的。

std::async深入谈

std::async参数详解

std::async:是一个用来创建异步任务的函数模板。

作用: 启动一个异步任务,当把一个异步任务启动起来之后,它就会返回一个std::future对象。(std::future是一个类模板)(人话:开启一个线程,并用该线程的返回值创建一个future对象并返回)

std::async函数模板我们一般我认为他是创建一个异步任务的,而不称它是创建一个新的线程(虽然实际上它也可以创建新的线程)

std::async函数模板的参数:

  1. std::launch::deferred【延迟调用线程入口函数】
  2. std::launch::async【强制创建一个线程】

std::thread这个线程类在系统资源紧张的情况下,则会出现创建线程失败的情况。那么当我们执行std::thread线程类对象时,可能会导致整个程序都崩溃了的情况!

std::async和std::thread的区别

std::async和std::thread的最明显的不同是:有时std::async并不创建新的线程。

  1. 当async函数模板第一个参数使用std::launch::deferred时:会使得对应的线程入口函数被延迟调用,且不创建新的线程,延迟到future对象使用get()/wait()函数时才会执行任务入口函数,若没有使用get()/wait()函数,则程序不会执行线程入口函数了!

demo1:

#include<iostream>
#include<thread>
#include<atomic>
#include<future>
using namespace std;
int mythread(int val) {
	cout << "mythread start and mythread's thread id = " << std::this_thread::get_id() << endl;
	cout << "mythread end and mythread's thread id = " << std::this_thread::get_id() << endl;
	return val;
}
int main(void) {
	cout << "main start ! and main thread id = " << std::this_thread::get_id() << endl;
	std::future<int> fuobj(std::async(std::launch::deferred,mythread,8));
	auto res = fuobj.get();
	cout << "res = " << res << endl;
	cout << "main thread end! and main thread id = " << std::this_thread::get_id() << endl;
	return 0;
}

运行结果:

因为线程id是唯一的,so从上述运行结果可以看出std::async这个函数模板并没有创建新的线程!

  1. 当async函数模板第一个参数使用std::launch::async时:会强制async这个异步任务在新的线程上执行。这意味着系统必须创建出一个新的线程来运行线程入口函数。

demo2

#include<iostream>
#include<thread>
#include<atomic>
#include<chrono>
#include<future>
using namespace std;
int mythread(int val) {
	cout << "mythread start and mythread's thread id = " << std::this_thread::get_id() << endl;
	cout << "mythread end and mythread's thread id = " << std::this_thread::get_id() << endl;
	return val;
}
int main(void) {
	cout << "main start ! and main thread id = " << std::this_thread::get_id() << endl;
	std::future<int> fuobj(std::async(std::launch::async,mythread,8));
	std::chrono::seconds dura(5);
	std::this_thread::sleep_for(dura);
	auto res = fuobj.get();
	cout << "res = " << res << endl;
	cout << "main thread end! and main thread id = " << std::this_thread::get_id() << endl;
	return 0;
}

运行结果:

  1. 当async函数模板第一个参数使用std::launch::async | std::launch::deferred时:会导致不确定性问题。(既可能是以创建新线程的方式执行程序,又可能是以不创建新线程的方式执行程序这样的不确定性问题)。

其中,这个位或符号 “|”,意味着async这个模板函数的行为可能是:“创建新线程并立即执行”或者是没有创建新线程并且延迟到future对象调用get() / wait()函数才开始执行任务入口函数。创建新线程并执行对应的任务入口函数的方式我们称之为异步方式,不创建新线程但执行对应的任务入口函数的方式我们称之为同步方式。到底是异步还是同步呢?这由系统自己判断。

demo3

#include<iostream>
#include<thread>
#include<atomic>
#include<mutex>
#include<future>
using namespace std;
int mythread(int val) {
	cout << "mythread start and mythread's thread id = " << std::this_thread::get_id() << endl;
	cout << "mythread end and mythread's thread id = " << std::this_thread::get_id() << endl;
	return val;
}
int main(void) {
	cout << "main start ! and main thread id = " << std::this_thread::get_id() << endl;
	std::future<int> fuobj(std::async(std::launch::async | std::launch::deferred,mythread,8));
	auto res = fuobj.get();
	cout << "res = " << res << endl;
	cout << "main thread end! and main thread id = " << std::this_thread::get_id() << endl;
	return 0;
}

运行结果:

  1. async函数模板不带任何额外的参数,只给他一个线程入口函数名。此时就和第3种case加参数std::launch::async | std::launch::deferred的效果是完全一致的!系统会自行决定是异步(创建新线程)还是同步(不创建新线程)方式执行对应的任务入口函数的代码。

demo4

#include<iostream>
#include<thread>
#include<atomic>
#include<future>
using namespace 
int mythread(int val) {
	cout << "mythread start and mythread's thread id = " << std::this_thread::get_id() << endl;
	cout << "mythread end and mythread's thread id = " << std::this_thread::get_id() << endl;
	return val;
}
int main(void) {
	cout << "main start ! and main thread id = " << std::this_thread::get_id() << endl;
	std::future<int> fuobj(std::async(mythread,8));
    //==> 相当于加了std::launch::async | std::launch::deferred参数
	auto res = fuobj.get();
	cout << "res = " << res << endl;
	cout << "main thread end! and main thread id = " << std::this_thread::get_id() << endl;
	return 0;
}

运行结果:

std::async和std::thread的区别总结

使用std::thread创建线程的一般格式:

int mythread(){return 1;}//线程入口函数
std::thread mytobj(mythread);
mytobj.join();
  • std::thread创建线程时,如果系统资源紧张,则创建线程失败,那么整个程序就会报异常崩溃!
  • std::thread创建线程的方式要想拿到对应的线程入口函数的返回值是不容易的!

使用std::async创建线程的一般格式:

int mythread(){return 1;}//线程入口函数
std::future fuobj(std::async(mythread));
fuobj.get();
  • std::async创建异步任务。可能创建也可能不创建线程,并且,async的调用方法很容易拿到线程入口函数的返回值!只要把async对象绑定到future 或者 shared_future对象身上再用.get()函数就能拿到返回值了!

由于系统资源的限制:

  1. 如果用std::thread创建的线程太多,则可能会创建失败,此时系统就会报告异常,崩溃!
  2. 如果用std::async,一般就不会报异常也不会崩溃。因为即便是系统资源紧张导致无法创建新线程时,调用不加额外参数的async函数,也不会创建新线程。而后续在哪个线程上的future或者shared_future对象调用了get()函数取得任务入口函数的返回值时,那么这个异步任务mythread就会运行在执行该get()函数的线程上了!当然,如果你强制async函数一定要创建新的线程,那就必须使用额外参数std::launch::async。此时你承受的代价就是系统资源紧张时,程序会崩溃!

经验:一般一个程序里,线程数量不宜超过100-200个!(当然,这需要你在实际的项目开发中自己去试,试出运行效率最佳的线程数量!)

std::async不确定问题的解决(重要)

不确定问题产生的原因:当async函数模板不带任何额外的参数,只给他一个线程入口函数名。此时就和加参数std::launch::async | std::launch::deferred的效果是完全一致的!系统会自行决定是异步(创建新线程)还是同步(不创建新线程)方式执行对应的任务入口函数的代码。此时,我们就可能会犯错!当系统选择以创建新线程的方式运行时,后续我以不创建新线程的方式来写代码,或者说系统选择以不创建新线程的方式来运行时,后续我以创建新线程的方式来写代码。 这样都会导致你的程序异常!

如何解决不确定性问题:用future或者shared_future对象的wait_for()函数!帮助我们查看async函数是采用了std::launch::async还是std::launch::deferred策略!以便我们用采取合适的方式来写后续的代码!

注意:千万不要想当然地认为async函数一定会为我们创建一个新的线程,还有线程入口函数被延迟执行的可能!因此需要非常谨慎地使用async!做好2种情况的分类讨论,此时你写的代码就不会出现大问题了!

#include<iostream>
#include<thread>
#include<atomic>
#include<chrono>
#include<future>
using namespace std;
int mythread(int val) {
	cout << "mythread start and mythread's thread id = " << std::this_thread::get_id() << endl;
	std::chrono::seconds dura(5);
	std::this_thread::sleep_for(dura);
	cout << "mythread end and mythread's thread id = " << std::this_thread::get_id() << endl;
	return val;
}
int main(void) {
	cout << "main start ! and main thread id = " << std::this_thread::get_id() << endl;
	std::shared_future<int> result(std::async(mythread,8));//std::launch::deferred,
	//这里使用wait_for就是用来判断async函数到底有没有创建新的子线程(系统决定)
	//从而可以帮助我们选择何种方式来写后续的代码了!
	std::future_status status = result.wait_for(3s);//等待0s钟 ==> std::chrono::seconds(0)
	if (status == std::future_status::deferred) {
		//此时系统资源紧张了,线程入口函数被延迟执行!系统给我采用std::launch::deferred策略了!
		//==>相当于async函数的第一个额外参数被设置为std::launch::deferred
		cout << "子线程被延迟执行!" << endl;//此时,因为get函数是在主线程中执行的,因此就不会再执行子线程了!!
		auto res = result.get();//此时才会去调用被延迟的mythread线程入口函数,但是是在主线程中调用的!
		cout << "res = " << res << endl;
	}
	else {
		//此时表示系统资源不紧张,async函数已经创建出新的线程了!
		if (status == std::future_status::timeout) {
			//等了6s子线程还没有执行完毕!超时了!
			cout << "超时!线程还没执行完毕呢!" << endl;
			auto res = result.get();//虽然没执行完成,但是我还可以用.get()成员函数等待这个线程入口函数执行完毕!
			cout << "res = " << res << endl;
		}
		else if (status == std::future_status::ready) {
			//子线程成功返回
			cout << "子线程成功执行完毕并返回!" << endl;
			auto res = result.get();
			cout << "res = " << res << endl;
		}
	}
	cout << "main thread end! and main thread id = " << std::this_thread::get_id() << endl;
	return 0;
}