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

#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

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值