在 C++ 中,可以使用标准库中的 std::thread 创建线程,并使用互斥锁 std::mutex 来实现线程间的同步。

下面是一个示例代码,其中一个线程负责写入数据到共享变量中,另一个线程负责读取共享变量的值:

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;
int sharedData = 0;

void writerThread() {
    for (int i = 0; i < 5; ++i) {
        std::lock_guard<std::mutex> lock(mtx); // 加锁
        sharedData = i;
        std::cout << 'Writer thread wrote: ' << i << std::endl;
    }
}

void readerThread() {
    for (int i = 0; i < 5; ++i) {
        std::lock_guard<std::mutex> lock(mtx); // 加锁
        std::cout << 'Reader thread read: ' << sharedData << std::endl;
    }
}

int main() {
    std::thread writer(writerThread);
    std::thread reader(readerThread);
    
    writer.join();
    reader.join();
    
    return 0;
}

在上面的代码中,writerThread 负责写入数据到 sharedData 变量中,而 readerThread 负责读取 sharedData 的值。为了确保线程安全,我们使用了 std::mutex 来保护共享变量的访问,通过 std::lock_guard 来自动加锁和解锁。

输出结果可能是:

Writer thread wrote: 0
Reader thread read: 0
Writer thread wrote: 1
Reader thread read: 1
Writer thread wrote: 2
Reader thread read: 2
Writer thread wrote: 3
Reader thread read: 3
Writer thread wrote: 4
Reader thread read: 4

这样就实现了一个线程读取另一个线程的功能。


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

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