线程经典使用方法

线程经典使用方法

概述

这份代码演示 std::thread + std::condition_variable条件变量 + std::atomic原子变量 的经典生产者‑消费者线程同步模型。

  • sound_thread:工作线程,等待条件唤醒,执行业务;
  • record_thread:触发线程,周期性发送信号唤醒工作线程;

头文件说明

表格

头文件 作用
<atomic> 提供std::atomic原子变量,无锁多线程安全读写
<thread> C++ 标准线程库,std::thread、std::this_thread
<condition_variable> 条件变量,实现线程等待 / 唤醒
<mutex> 互斥锁,配合条件变量使用
<iostream> 控制台输出
<fstream> 文件流(本代码未使用)
<nlohmann/json.hpp> json 库头,本示例仅引入,没有业务调用

全局静态变量

static std::atomic<bool> g_sound_running(false);        // 总开关:控制sound_thread线程是否继续运行
static std::atomic<bool> g_sound_thread_active(false);   // 业务标志位:是否需要执行一次sound业务逻辑
static std::condition_variable g_sound_active_cv;        // 条件变量:用于阻塞/唤醒sound_thread
static std::mutex g_sound_active_mutex;                  // 和条件变量配对的互斥锁

注意:std::condition_variable必须搭配 mutex 使用,不能单独 notify‑wait。
std::atomic保证多线程读写不会发生数据竞争,不需要加锁。

sound_thread 工作线程

static void sound_thread(void *args) {
    g_sound_running.store(true);
    while (g_sound_running.load(std::memory_order_relaxed)) {
        {
            std::unique_lock<std::mutex> lock(g_sound_active_mutex);
            g_sound_active_cv.wait(lock, []() {
                return !g_sound_running.load(std::memory_order_acquire) ||
                       g_sound_thread_active.load(std::memory_order_acquire);
            });
        }
        std::cout << "soundHandle success..." << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
        g_sound_thread_active.store(false);
    }
}

逻辑拆解

  1. g_sound_running.store(true); 设置线程运行标记;
  2. while 循环:只要总开关g_sound_running=true就一直循环;
  3. std::unique_lock<std::mutex> lock(g_sound_active_mutex) 获取互斥锁;
  4. cv.wait(lock, 谓词lambda)
    • wait 会释放锁,阻塞当前线程,等待 notify 唤醒;
    • 被唤醒后会重新拿到锁,执行 lambda 判断条件;
    • lambda 返回 false → 继续等待;返回 true → wait 函数返回,线程向下执行。

等待条件二选一即可唤醒:

  • !g_sound_running.load():总开关关闭,线程需要退出;
  • g_sound_thread_active.load():收到业务激活信号,执行业务。
  1. 打印业务日志,模拟业务耗时sleep_for(10ms);
  2. g_sound_thread_active.store(false):清除业务标记,等待下一次唤醒。

内存序说明:

  • memory_order_acquire读:保证后面代码不会被 CPU 重排到读取之前;
  • memory_order_release写:保证前面代码不会被 CPU 重排到写入之后;
  • memory_order_relaxed只保证原子性,不做内存屏障。

record_thread 触发线程

static void record_thread(void *args) {
    while (true) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        g_sound_thread_active.store(true, std::memory_order_release);
        std::lock_guard<std::mutex> lock(g_sound_active_mutex);
        g_sound_active_cv.notify_all();
    }
}
  1. 死循环,每 1 秒钟执行一次;
  2. g_sound_thread_active.store(true) 设置业务激活标记,release 内存序,让另外线程可见;
  3. std::lock_guard锁住互斥锁;
  4. notify_all()唤醒所有等待该条件变量的线程,这里唤醒sound_thread。

最佳实践:notify_all()的时候最好持有锁,可以避免虚假唤醒带来的部分诡异问题;也可以用 notify_one (),只唤醒一个等待线程。

image
image

#include <atomic>
#include <iostream>
#include <fstream>
#include <condition_variable>
#include <thread>
#include <nlohmann/json.hpp>

static std::atomic<bool> g_sound_running(false);
static std::atomic<bool> g_sound_thread_active(false);
static std::condition_variable g_sound_active_cv;
static std::mutex g_sound_active_mutex;


static void sound_thread(void *args) {
    g_sound_running.store(true);
    while (g_sound_running.load(std::memory_order_relaxed)) {
        {
            std::unique_lock<std::mutex> lock(g_sound_active_mutex);
            g_sound_active_cv.wait(lock, []() {
                return !g_sound_running.load(std::memory_order_acquire) ||
                       g_sound_thread_active.load(std::memory_order_acquire);
            });
        }

        std::cout << "soundHandle success..." << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
        g_sound_thread_active.store(false);
    }
}


static void record_thread(void *args) {
    while (true) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));

        g_sound_thread_active.store(true, std::memory_order_release);
        std::lock_guard<std::mutex> lock(g_sound_active_mutex);
        g_sound_active_cv.notify_all();
    }
}

int main() {

    std::thread t1(sound_thread, nullptr);
    std::thread t2(record_thread, nullptr);

    t1.join();
    t2.join();

    return 0;
    // TIP 请访问 <a href="https://www.jetbrains.com/help/clion/">jetbrains.com/help/clion/</a> 查看 CLion 帮助。此外,您还可以从主菜单中选择“帮助 | 学习 IDE 功能”,尝试 CLion 的交互式课次。
}

posted @ 2026-11-09 10:19  流逝的轻风  阅读(11)  评论(0)    收藏  举报