一个使用自定义原子类型的例子是多线程环境下的计数器。在C++中,我们可以使用std::atomic模板类来创建原子类型。下面的示例中,我们使用自定义的原子类型AtomicCounter来实现一个线程安全的计数器:

#include <iostream>
#include <atomic>
#include <thread>

// 自定义原子类型
class AtomicCounter {
public:
    AtomicCounter() : count(0) {}

    void increment() {
        count.fetch_add(1, std::memory_order_relaxed);
    }

    void decrement() {
        count.fetch_sub(1, std::memory_order_relaxed);
    }

    int getCount() const {
        return count.load(std::memory_order_relaxed);
    }

private:
    std::atomic<int> count;
};

int main() {
    AtomicCounter counter;

    // 创建多个线程对计数器进行操作
    std::thread t1([&counter]() {
        for (int i = 0; i < 10000; ++i) {
            counter.increment();
        }
    });

    std::thread t2([&counter]() {
        for (int i = 0; i < 10000; ++i) {
            counter.increment();
        }
    });

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

    // 输出最终的计数值
    std::cout << "Count: " << counter.getCount() << std::endl;

    return 0;
}

在上面的示例中,我们创建了一个AtomicCounter类,它包含一个std::atomic类型的成员变量count。AtomicCounter类提供了increment()、decrement()和getCount()等方法来对计数器进行操作。这些操作都是原子的,因此可以在多线程环境中安全地对计数器进行递增和递减操作。

在主函数中,我们创建了两个线程t1和t2,它们分别对计数器进行递增操作。最后,我们输出计数器的最终值。由于std::atomic类型提供了原子操作的保证,因此计数器是线程安全的,输出的结果应该为20000。

c++举一个用自定义原子类型的例子

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

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