RAII。

这是一个概念,后面会用到。Resource Acquisition Is Initialization. 资源获取既初始化。

扩展书中给出的代码示例,

demo01,

/*
    这个代码完全是串行的,
    因为在循环里面,整个循环完全结束了,那么 mutetx 才会释放
*/
#define _CRT_SECURE_NO_WARNINGS

#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>

std::mutex m;  // used to protect access to shared data

int shared_data = 0;

void increment(int n) {
    auto id = std::this_thread::get_id();
    std::unique_lock<std::mutex> lck(m);  // acquire mutex
    for (int i = 0; i < n; ++i) {
        shared_data++;
        std::cout << id << " => " << shared_data << '\\n';
    }
}

int main() {
    freopen("./demo01.txt", "w", stdout);
    std::cout << std::thread::hardware_concurrency() << '\\n';  // 查看默认线程限制
    std::thread t1(increment, 100000);
    std::thread t2(increment, 100000);

    t1.join();
    t2.join();

    std::unique_lock<std::mutex> lck(m);
    std::cout << "shared_data: " << shared_data << "\\n";

    return 0;
}

demo02, 这个 demo 和下面的 demo03 都是可以去抢锁的,

/*
    这个代码修改了作用域,没出一次循环,lck 的析构函数就自己释放一次
*/
#define _CRT_SECURE_NO_WARNINGS

#include <chrono>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>

std::mutex m;  // used to protect access to shared data

int shared_data = 0;

void increment(int n) {
    auto id = std::this_thread::get_id();
    for (int i = 0; i < n; ++i) {
        {
            std::unique_lock<std::mutex> lck(m);  // acquire mutex
            shared_data++;
            std::cout << id << " => " << shared_data << '\\n';
        }
    }
}

int main() {
    freopen("./demo01_v02.txt", "w", stdout);
    std::cout << std::thread::hardware_concurrency() << '\\n';  // 查看默认线程限制
    std::thread t1(increment, 100000);
    std::thread t2(increment, 100000);

    t1.join();
    t2.join();

    std::unique_lock<std::mutex> lck(m);
    std::cout << "shared_data: " << shared_data << "\\n";

    return 0;
}

demo03,

/*
    加了一对花括号,其实效果应该是一样的
*/
#define _CRT_SECURE_NO_WARNINGS

#include <chrono>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>

std::mutex m;  // used to protect access to shared data

int shared_data = 0;

void increment(int n) {
    auto id = std::this_thread::get_id();
    for (int i = 0; i < n; ++i) {
        std::unique_lock<std::mutex> lck(m);  // acquire mutex
        shared_data++;
        std::cout << id << " => " << shared_data << '\\n';
    }
}

int main() {
    freopen("./demo01_v03.txt", "w", stdout);
    std::cout << std::thread::hardware_concurrency() << '\\n';  // 查看默认线程限制
    std::thread t1(increment, 100000);
    std::thread t2(increment, 100000);

    t1.join();
    t2.join();

    std::unique_lock<std::mutex> lck(m);
    std::cout << "shared_data: " << shared_data << "\\n";

    return 0;
}