C ++ 11使用< atomic> [英] C++11 Implementation of Spinlock using <atomic>

查看:136
本文介绍了C ++ 11使用< atomic>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了SpinLock类,如下

I implemented SpinLock class, as followed

struct Node {
    int number;
    std::atomic_bool latch;

    void add() {
        lock();
        number++;
        unlock();
    }
    void lock() {
        bool unlatched = false;
        while(!latch.compare_exchange_weak(unlatched, true, std::memory_order_acquire));
    }
    void unlock() {
        latch.store(false , std::memory_order_release);
    }
};

我在类上面实现了两个线程,它们调用Node类的同一个实例的add()方法每线程1000万次。

I implemented above class and made two threads which call add() method of a same instance of Node class 10 million times per thread.

结果是,不幸的是,不是2000万。
我在这里缺少什么?

the result is , unfortunately, not 20 million. What am I missing here?

推荐答案

问题是 compare_exchange_weak 更新 unlatched 变量失败。从 compare_exchange_weak 的文档:

The problem is that compare_exchange_weak updates the unlatched variable once it fails. From the documentation of compare_exchange_weak:


比较原子对象的包含值with
expected:
- 如果为true,它用val(like store)替换包含的值。
- 如果为false,则用期望值替换包含的值。

首先失败的 compare_exchange_weak 未锁定将更新为 true 因此下一个循环迭代将尝试 compare_exchange_weak true true

I.e., after the first failing compare_exchange_weak, unlatched will be updated to true, so the next loop iteration will try to compare_exchange_weak true with true. This succeeds and you just took a lock that was held by another thread.

解决方案:
确保设置未锁定返回之前 compare_exchange_weak 之前的 false ,例如:

Solution: Make sure to set unlatched back to false before each compare_exchange_weak, e.g.:

while(!latch.compare_exchange_weak(unlatched, true, std::memory_order_acquire)) {
    unlatched = false;
}

这篇关于C ++ 11使用< atomic>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆