在 C++ 中,主线程和其他线程之间的通信可以通过共享数据来实现。以下是一个示例代码,展示了主线程如何读取由另一个线程填充的数据:

#include <iostream>
#include <thread>
#include <chrono>

bool dataReady = false;
int sharedData = 0;

void workerThread()
{
    // 模拟耗时操作
    std::this_thread::sleep_for(std::chrono::seconds(2));
    
    // 填充数据
    sharedData = 42;
    
    // 设置数据已准备好的标志
    dataReady = true;
}

int main()
{
    // 创建工作线程
    std::thread worker(workerThread);
    
    // 主线程等待数据准备好
    while (!dataReady)
    {
        // 等待数据准备好
    }
    
    // 读取数据
    int result = sharedData;
    
    // 输出数据
    std::cout << 'Data received: ' << result << std::endl;
    
    // 等待工作线程完成
    worker.join();
    
    return 0;
}

在上述示例中,主线程通过循环等待数据准备好的标志'dataReady'为'true'来等待工作线程填充数据。一旦数据准备好,主线程就可以读取共享数据'sharedData'。最后,主线程等待工作线程完成并回收资源。

需要注意的是,这只是一种简单的线程间通信方式。在实际应用中,可能需要考虑线程同步、互斥锁等更复杂的问题。


原文地址: https://www.cveoy.top/t/topic/o1ej 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录