C++11使用mutex和condition_variable实现线程同步

C++11使用mutex和condition_variable实现线程同步

在实现项目的过程中,突然有一个问题:

C++中A、B、C三个线程模拟购买100张车票,A输出99,B输出98,C输出97,然后又循环A输出96,B95,C94,直到0,使用线程同步,如何实现?

这是一种按顺序执行线程的问题,应该实现?

代码如下:

#include 
#include 
#include 
#include 
#include 

// 共享资源:车票数量
std::atomic ticket_count(100);

// 互斥锁和条件变量
std::mutex mtx;
std::condition_variable cv;
int turn = 0;  // 当前轮到哪个线程执行,0: A, 1: B, 2: C

// 线程函数:模拟购买车票
void buyTickets(const std::string& thread_name, int id) {
    while (true) {
        std::unique_lock lock(mtx);
        cv.wait(lock, [id] { return turn == id; });  // 等待轮到当前线程执行

        if (ticket_count > 0) {
            // 模拟购买一张车票
            int current_ticket = ticket_count--;
            std::cout << thread_name << " bought ticket " << current_ticket << std::endl;

            // 更新turn,切换到下一个线程
            turn = (turn + 1) % 3;
            cv.notify_all();  // 通知其他线程
        } else {
            std::cout << thread_name << " found no more tickets to buy." << std::endl;
            break;  // 如果没有车票了,退出循环
        }
    }
}

int main() {
    // 创建三个线程
    std::thread threadA(buyTickets, "Thread A", 0);
    std::thread threadB(buyTickets, "Thread B", 1);
    std::thread threadC(buyTickets, "Thread C", 2);

    // 等待所有线程完成
    threadA.join();
    threadB.join();
    threadC.join();

    std::cout << "All threads finished buying tickets. Total tickets sold: " << (100 - ticket_count) << std::endl;

    return 0;
}

代码说明

  1. 线程调度顺序
    • 使用全局变量turn来记录当前轮到哪个线程执行(0表示线程A,1表示线程B,2表示线程C)。
    • 每个线程在进入临界区后,会通过条件变量cv.wait检查是否轮到自己执行。如果不是,线程会阻塞。
  2. 条件变量
    • 条件变量cv用于线程间的协作。当一个线程完成操作后,会通过cv.notify_all唤醒所有等待的线程。
    • 唤醒后,线程会再次检查条件(turn == id),只有轮到自己的线程才会继续执行。
  3. 线程函数
    • 每个线程在购买车票后,会更新turn变量,切换到下一个线程的执行顺序。
    • 如果车票数量为0,线程会退出循环。
  4. 线程创建与同步
    • 使用std::thread创建三个线程,分别代表A、B、C。
    • 使用join方法等待所有线程完成。

代码运行结果:

C++11使用mutex和condition_variable实现线程同步_第1张图片

你可能感兴趣的:(C++基础,c++)