std::mutex

91 阅读1分钟

以下是一个简单的示例,演示了如何在 C++ 中使用互斥锁 (std::mutex) 来保护共享资源:

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

// 共享资源
int sharedData = 0;

// 互斥锁
std::mutex mtx;

// 线程函数,对共享资源进行操作
void threadFunction(int id) {
    for (int i = 0; i < 5; ++i) {
        // 使用互斥锁保护共享资源
        mtx.lock();
        std::cout << "Thread " << id << " accessing shared data: " << sharedData << std::endl;
        ++sharedData;
        std::cout << "Thread " << id << " updated shared data: " << sharedData << std::endl;
        mtx.unlock();
        
        // 模拟一些工作
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

int main() {
    // 创建两个线程
    std::thread t1(threadFunction, 1);
    std::thread t2(threadFunction, 2);

    // 等待线程执行完成
    t1.join();
    t2.join();

    return 0;
}

在这个示例中,有两个线程同时访问共享资源 sharedData。为了确保线程安全,我们使用了 std::mutex 来保护对共享资源的访问。在每个线程的执行循环中,首先调用 lock() 方法来获取互斥锁,然后对共享资源进行操作,最后调用 unlock() 方法来释放互斥锁。

这样做可以确保同时只有一个线程可以访问共享资源,从而避免了竞态条件(Race Condition)的发生,保证了线程安全性。