C++并发学习一:实现线程安全的计数器

这里使用加锁实现,注意读取(getValue())也要加锁,因为多核CPU架构下,一个Core的写入不一定立刻对另一个Core有限(因为CPU缓存),所以需要加锁(或其他内存屏障操作)以确保内存可见性,保证其他线程能读到被修改后的最新值

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

// 一个不安全的计数器
struct UnsafeCounter {
    int value = 0;
    void increment() {
        value++;
    }
};

// TODO: 实现一个线程安全的计数器
class SafeCounter {
public:
    SafeCounter() : value_(0) {}

    void increment() {
        std::lock_guard<std::mutex> lock(mutex_);
        value_++;
    }

    int getValue() {
        std::lock_guard<std::mutex> lock(mutex_);
        return value_;
    }

private:
    int value_;
    std::mutex mutex_;
};

int main(int argc, char* argv[]) {
    const int num_threads = 100;
    const int increments_per_thread = 100000;

    SafeCounter counter;
    std::vector<std::thread> threads;

    for (int i = 0; i < num_threads; i++) {
        threads.emplace_back([&counter, increments_per_thread]() {
            for (int j = 0; j < increments_per_thread; j++) {
                counter.increment();
            }
        });
    }

    for (auto& t : threads) {
        t.join();
    }

    std::cout << "Expected value: " << num_threads * increments_per_thread << std::endl;
    std::cout << "Actual value:   " << counter.getValue() << std::endl;

    return 0;
}
posted @ 2025-11-11 10:35  KBZ232  阅读(9)  评论(0)    收藏  举报