C++ 11 线程同步(一)

[参考](32 C++ 两个线程轮流(交替)打印 A 和 B - 知乎 (zhihu.com)

C++ 11 特性

1、

两个线程分别打印 A、B

#include<iostream>
#include<thread>

void Producer() {
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout << "A" << std::endl;
    }
}

void Consumer() {
    while (1)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout << "B" << std::endl;
    }
}

int main() {
    std::thread t1(Producer);
    std::thread t2(Consumer);
    t1.join();
    t2.join();
    std::cin.get();
    // return 0;
}

运行结果:

A
B
A
B
AB

A
B
BA

^C

2、

两个线程分别轮流打印 A、B

#include<iostream>
#include<mutex>
#include<thread>
#include<condition_variable>

std::mutex mtx;
std::condition_variable cv;
std::string flag("A");

void printA() {
    while (1) {
        std::unique_lock<std::mutex> lock(mtx);
        if (flag == "B") {
            cv.wait(lock);
        }

        std::cout << "AA" << std::endl;
        flag = "B";
        cv.notify_all();
    }
}

void printB() {
    while (1) {
        std::unique_lock<std::mutex> lock(mtx);
        if (flag == "A") {
            cv.wait(lock);
        }

        std::cout << "BB" << std::endl;
        flag = "A";
        cv.notify_all();
    }
}

int main() {
    std::thread t1(printA);
    std::thread t2(printB);
    t1.join();
    t2.join();
    std::cin.get();
    return 0;
}

打印结果:

AA
BB
AA
BB
AA
BB
AA
BB
AA
BB
AA
BB
AA
BB
AA
BB
^C

注释:

std::mutex 是 C++ 11 中最基本的互斥量,提供了独占所有权的特性;

std::unique_lock 是对 std::mutex 类型的互斥量的上锁和解锁进行管理

std::condition_variable 是条件变量,所有等待 (wait) 某个条件的线程都必须使用相同的 mutex, 且必须使用 unique_lock 绑定 mutex ,并且让 wait 等待在 unique_lock 上,否则会发生不明确的行为;

notify_one() 随机通知某一个等待的线程,notify_all() 通知所有等待的线程 

原文地址:https://www.cnblogs.com/wanghao-boke/p/15425746.html