C++ 标准库 线程库和条件变量的使用demo

发布时间:2024年01月19日
#include <iostream>                // std::cout
#include <thread>                // std::thread
#include <mutex>                // std::mutex, std::unique_lock
#include <condition_variable>    // std::condition_variable
 
std::mutex mtx; // 全局互斥锁.
std::condition_variable cv; // 全局条件变量.
bool ready = false; // 全局标志位.
 
void do_print_id(int id)
{
    std::unique_lock <std::mutex> lck(mtx);
    std::cout << "thread " << id << " get mutex priority" << std::endl;
    while (!ready) // 如果标志位不为 true, 则等待...
    {
        std::cout << "thread " << id << " waiting" << std::endl;
        cv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后,

    }
    // 线程被唤醒, 继续往下执行打印线程编号id.
    std::cout << "thread " << id << '\n';
}
 
void go()
{
    std::unique_lock <std::mutex> lck(mtx);
    ready = true; // 设置全局标志位为 true.
    cv.notify_all(); // 唤醒所有线程.
}
 
int main()
{
    std::thread threads[10];
    // spawn 10 threads:
    for (int i = 0; i < 10; ++i)
        threads[i] = std::thread(do_print_id, i);
 
    std::cout << "10 threads ready to race...\n";
    go(); // go!
 
  for (auto & th:threads)
        th.join();
 
    return 0;
}

cmake_minimum_required(VERSION 3.12)
project(ThreadExample)

# 设置 C++ 标准
set(CMAKE_CXX_STANDARD 11)

# 添加可执行文件
add_executable(ThreadExample test.cpp)

# 查找线程库
find_package(Threads REQUIRED)

# 链接线程库
target_link_libraries(ThreadExample PRIVATE Threads::Threads)

输出

root@qlz:~/workspace/apps/test/build# ./ThreadExample 
thread 0 get mutex priority
thread 0 waiting
thread 1 get mutex priority
thread 1 waiting
thread 2 get mutex priority
thread 2 waiting
thread 3 get mutex priority
thread 3 waiting
thread 4 get mutex priority
thread 4 waiting
thread 6 get mutex priority
thread 6 waiting
thread 5 get mutex priority
thread 5 waiting
thread 7 get mutex priority
thread 7 waiting
10 threads ready to race...
thread 8 get mutex priority
thread 8 waiting
thread 1
thread 7
thread 2
thread 0
thread 6
thread 4
thread 3
thread 5
thread 9 get mutex priority
thread 9
thread 8
root@qlz:~/workspace/apps/test/build#

参考

https://www.cnblogs.com/haippy/p/3235560.html

文章来源:https://blog.csdn.net/flying_ant2018/article/details/135698793
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。