C++ 不同线程之间传值

不同线程之间传值,常见有以下五种安全可靠 的方式,避免用全局变量裸暴露


通过线程函数参数传值(最基本)

cpp 复制代码
#include <iostream>
#include <thread>

void threadFunc(int val) {
    std::cout << "Thread received: " << val << std::endl;
}

int main() {
    int value = 42;
    std::thread t(threadFunc, value);
    t.join();
}

⚠️注意:传入的是拷贝,若想共享变量,需用引用或指针。


通过 std::ref 传引用

cpp 复制代码
#include <iostream>
#include <thread>

void threadFunc(int& val) {
    val += 10;
}

int main() {
    int value = 42;
    std::thread t(threadFunc, std::ref(value));
    t.join();
    std::cout << value << std::endl;  // 输出 52
}

⚠️多线程修改同一变量,要加锁。


共享数据 + 互斥锁 std::mutex 保护

cpp 复制代码
#include <iostream>
#include <thread>
#include <mutex>

int sharedData = 0;
std::mutex mtx;

void threadFunc() {
    std::lock_guard<std::mutex> lock(mtx);
    sharedData += 1;
}

int main() {
    std::thread t1(threadFunc);
    std::thread t2(threadFunc);
    t1.join();
    t2.join();
    std::cout << sharedData << std::endl;
}

使用 std::condition_variable 通知传值

线程A生产数据,线程B等待并消费:

cpp 复制代码
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

int data = 0;
bool ready = false;
std::mutex mtx;
std::condition_variable cv;

void producer() {
    {
        std::lock_guard<std::mutex> lock(mtx);
        data = 42;
        ready = true;
    }
    cv.notify_one();
}

void consumer() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [] { return ready; });
    std::cout << "Received data: " << data << std::endl;
}

int main() {
    std::thread t1(consumer);
    std::thread t2(producer);
    t1.join();
    t2.join();
}

线程安全队列传值(推荐,解耦好)

比如:

cpp 复制代码
#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>

std::queue<int> msgQueue;
std::mutex mtx;
std::condition_variable cv;

void producer() {
    for (int i = 0; i < 5; ++i) {
        {
            std::lock_guard<std::mutex> lock(mtx);
            msgQueue.push(i);
        }
        cv.notify_one();
    }
}

void consumer() {
    for (int i = 0; i < 5; ++i) {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, [] { return !msgQueue.empty(); });
        int val = msgQueue.front();
        msgQueue.pop();
        std::cout << "Consumed: " << val << std::endl;
    }
}

int main() {
    std::thread t1(consumer);
    std::thread t2(producer);
    t1.join();
    t2.join();
}

总结建议

需求 推荐方式
简单只传一次值 线程参数或 std::ref
多次共享或修改数据 共享变量 + std::mutex
需要通知、等待 std::condition_variable
大量数据流、解耦需求 线程安全队列(配合锁或封装类)

你如果告诉我具体场景(比如:线程A接收串口数据,线程B处理,线程C保存文件),我可以帮你出针对性的设计方案。你要举例吗?

相关推荐
微三云生态系统架构师-彭丹8 小时前
矩阵拼团系统设计:先付款先排队的订单排序与自动返本算法
线性代数·算法·矩阵
@MMiL8 小时前
基于Keil 的实时参数标定和值观测
算法
名字还没想好☜8 小时前
Go 标准库 flag 包实战:参数解析、子命令、自定义 Value 类型与默认值
开发语言·后端·golang·go
j7~9 小时前
【C++】C++的IO流--详解
c++·c++io流·c++流的概念·stringstream的介绍·c语言的输入与输出
公爵爱学习9 小时前
无人机定点飞行-介绍
开发语言·图像处理·python·学习·线性回归·无人机
西西弗Sisyphus9 小时前
Qt 分类导航区的实现
开发语言·qt
zhanghaha13149 小时前
Python进阶教程:27_subprocess 模块 零基础超详细教程
开发语言·python
兄弟加油,别颓废了。9 小时前
bugku题目
开发语言·前端·python
zh_xuan9 小时前
c++ string_view
开发语言·c++
阿里嘎多学长9 小时前
2026-09-05 GitHub 热点项目精选
开发语言·程序员·github·代码托管