llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
27.82k stars 11.46k forks source link

[TSAN] atomic will cause data race undetected. #62371

Open JackyWoo opened 1 year ago

JackyWoo commented 1 year ago

Env

$ clang -v
Ubuntu clang version 15.0.7
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/10
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/11
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/9
Selected GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/11
Candidate multilib: .;@m64
Selected multilib: .;@m64

Test case

  1. Data race detected

    // bad case: data race detected
    void testDataRace()
    {
    int32_t counter = 0;
    
    std::thread t1([&counter] {
        if (!counter)
            counter = 1;
    });
    std::thread t2([&counter] {
        if (!counter)
            counter = 2;
    });
    
    t1.join();
    t2.join();
    }
  2. Not detected when use atomic

    // For user it is a bad case, but not detected
    void testDataRaceAtomic()
    {
    std::atomic<int32_t> counter = 0;
    
    std::thread t1([&counter] {
        if (!counter)
            counter = 1;
    });
    std::thread t2([&counter] {
        if (!counter)
            counter = 2;
    });
    
    t1.join();
    t2.join();
    }

As a user's perspective the behavior is unexpected.

EugeneZelenko commented 1 year ago

Could you please try 16 or main branch?

HolyBlackCat commented 1 year ago

It still happens in trunk, but it doesn't look like a bug to me.

From what I understand, TSAN only detects data races (as in, the kind of UB), not race conditions in general (as in, logic errors in concurrent code that are not UB per se). (1, 2)

JackyWoo commented 1 year ago

@HolyBlackCat Thanks for reply. I wonder whether TSAN will detect data conditions.