#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#
参考