[SOLVED]Spinlock mutex not working with std::scoped_lock or std::lock_guard

I can call lock and unlock manually around the critical region and it works fine, but when I wrap it with a scoped_lock I still get a data race:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <atomic>
#include <iostream>
#include <thread>
#include <mutex>
struct spinlock_mutex
{
    void lock()
    {
        while(std::atomic_flag_test_and_set_explicit(&mut,
                std::memory_order_acquire)){}
    }
    void unlock()
    {
        std::atomic_flag_clear_explicit(&mut, std::memory_order_release);
    }
private:
    std::atomic_flag mut{ATOMIC_FLAG_INIT};
};

spinlock_mutex m;
double c = 0;
void increment(){ std::scoped_lock /*EDIT: I Forgot to name it here*/(m); for(int i = 0; i < 100000; ++i) c = c+1;}
#include <vector>
int main()
{
    std::vector<std::thread> vec;
    for(int i = 0; i < 5; ++i) vec.emplace_back(increment);
    for(auto&& i : vec) i.join();
    std::cout << "C is " << c << std::endl;
}


EDIT: D'oh! Just noticed that the scoped_lock is unnamed, thus it destructs immediately. If I add a name after scoped_lock it works. Leaving this thread here if someone has the same problem.
Last edited on
Topic archived. No new replies allowed.