#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.