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保存文件),我可以帮你出针对性的设计方案。你要举例吗?

相关推荐
ZealSinger1 小时前
Go1.25容器感知GOMAXPROCS避限流
java·开发语言
kiracrimson2 小时前
希尔排序:让插入排序不再怕逆序
数据结构·算法·排序算法
茉莉玫瑰花茶2 小时前
GO [ 类型 ]
开发语言·数据库·golang
梅雅达编程笔记2 小时前
02_BeautifulSoup网页数据提取
开发语言·爬虫·python·beautifulsoup·数据采集
Escalating_xu2 小时前
【C 语言】深入理解指针(3):字符指针、数组指针、二维数组传参、函数指针与转移表
java·c语言·开发语言
垆边人似月.2 小时前
华为机考题:最小代价爬楼梯
c语言·c++
可涵不会debug2 小时前
C++ std::bind 实战教程:线程池、回调场景全覆盖
linux·开发语言·c++
不正经的码狗2 小时前
Java 开发环境搭建与 Eclipse 使用速通教程
java·开发语言·eclipse
yi0112 小时前
DAY17: LeetCode 139|单词拆分:从“把单词删掉”到用 DP 记录合法切口
人工智能·笔记·python·算法·leetcode·动态规划
阿钱真强道2 小时前
24 嵌入式操作系统 | 项目启动与环境准备(PyQt5 / Flask 两个“最小可跑“)
开发语言·qt·flask·架构设计·协议契约