簡體   English   中英

原子bool無法保護非原子計數器

[英]Atomic bool fails to protect non-atomic counter

我遇到了一個(基本的)自旋鎖互斥鎖的問題,似乎沒有按預期工作。

4個線程正在遞增受此互斥鎖保護的非原子計數器。 結果與使互斥體看起來破碎的預期結果不匹配。

示例輸出:

  result: 2554230
expected: 10000000

在我的環境中,它發生在以下條件下:

  • flagstd::atomic<bool> ,其他任何東西,比如std::atomic<int>std::atomic_flag (帶有test_and_set )都可以。

  • 使用gcc 6.3.1和-O3標志在X86_64上編譯

我的問題是,有什么可以解釋這種行為?

#include <iostream>
#include <vector>
#include <atomic>
#include <thread>
#include <mutex>
#include <assert.h>

class my_mutex {
    std::atomic<bool> flag{false};

public:
    void lock()
    {
        while (flag.exchange(true, std::memory_order_acquire));
    }

    void unlock()
    {
        flag.store(false, std::memory_order_release);
    }
};


my_mutex mut;
static int counter = 0;


void increment(int cycles)
{
    for (int i=0; i < cycles; ++i)
    {
        std::lock_guard<my_mutex> lck(mut);

        ++counter;
    }
}

int main()
{
    std::vector<std::thread> vec;
    const int n_thr = 4;
    const int n_cycles = 2500000;

    for (int i = 0; i < n_thr; ++i)
        vec.emplace_back(increment, n_cycles);

    for(auto &t : vec)
        t.join();

    std::cout << "  result: " << counter << std::endl;
    std::cout << "expected: " << n_cycles * n_thr << std::endl;
}

編輯

根據Voo的請求,這里是increment()的匯編輸出。

$ g++ -O3 increment.cpp
$ gdb a.out
Reading symbols from a.out...done.
(gdb) disassemble increment
Dump of assembler code for function increment(int):
   0x0000000000401020 <+0>:     mov    0x20122a(%rip),%ecx        # 0x602250 <_ZL7counter>
   0x0000000000401026 <+6>:     test   %edi,%edi
   0x0000000000401028 <+8>:     mov    $0x1,%edx
   0x000000000040102d <+13>:    lea    (%rdi,%rcx,1),%esi
   0x0000000000401030 <+16>:    jle    0x401058 <increment(int)+56>
   0x0000000000401032 <+18>:    nopw   0x0(%rax,%rax,1)
   0x0000000000401038 <+24>:    mov    %edx,%eax
   0x000000000040103a <+26>:    xchg   %al,0x20120c(%rip)        # 0x60224c <mut>
   0x0000000000401040 <+32>:    test   %al,%al
   0x0000000000401042 <+34>:    jne    0x401038 <increment(int)+24>
   0x0000000000401044 <+36>:    add    $0x1,%ecx
   0x0000000000401047 <+39>:    cmp    %ecx,%esi
   0x0000000000401049 <+41>:    mov    %ecx,0x201201(%rip)        # 0x602250 <_ZL7counter>
   0x000000000040104f <+47>:    movb   $0x0,0x2011f6(%rip)        # 0x60224c <mut>
   0x0000000000401056 <+54>:    jne    0x401038 <increment(int)+24>
   0x0000000000401058 <+56>:    repz retq
End of assembler dump.

你的代碼是正確的。 這是一個錯誤80004 - [6回歸]非原子加載在原子加載之前移動到std :: memory_order_acquire

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM