Skip to content

Instantly share code, notes, and snippets.

@kevgs
Created November 9, 2015 18:51
Show Gist options
  • Save kevgs/31a528aa442fd39f639a to your computer and use it in GitHub Desktop.
Save kevgs/31a528aa442fd39f639a to your computer and use it in GitHub Desktop.
#include <thread>
struct spin {
void lock() {
while (flag.test_and_set(std::memory_order_acquire))
;
}
void unlock() { flag.clear(std::memory_order_release); }
std::atomic_flag flag = ATOMIC_FLAG_INIT;
};
int main() {
auto counter = 0;
spin lock;
auto t = std::thread([&]() {
lock.lock();
++counter;
lock.unlock();
});
lock.lock();
++counter;
lock.unlock();
t.join();
return 0;
}
/*
g++ -std=c++14 -fsanitize=thread -g test.cc -lpthread && ./a.out
==================
WARNING: ThreadSanitizer: data race (pid=5795)
Read of size 4 at 0x7ffe877260dc by thread T1:
#0 main::{lambda()#1}::operator()() const <null> (a.out+0x0000004012ff)
#1 _M_invoke<> /usr/include/c++/5/functional:1531 (a.out+0x000000402b87)
#2 operator() /usr/include/c++/5/functional:1520 (a.out+0x000000402a7c)
#3 _M_run /usr/include/c++/5/thread:115 (a.out+0x00000040299a)
#4 <null> <null> (libstdc++.so.6+0x0000000b902f)
Previous write of size 4 at 0x7ffe877260dc by main thread:
#0 main /home/kevg/Desktop/test.cc:25 (a.out+0x0000004013ea)
Location is stack of main thread.
Thread T1 (tid=5797, running) created by main thread at:
#0 pthread_create <null> (libtsan.so.0+0x000000027aa7)
#1 std::thread::_M_start_thread(std::shared_ptr<std::thread::_Impl_base>, void (*)()) <null> (libstdc++.so.6+0x0000000b9172)
#2 main /home/kevg/Desktop/test.cc:22 (a.out+0x0000004013c0)
SUMMARY: ThreadSanitizer: data race ??:0 main::{lambda()#1}::operator()() const
==================
ThreadSanitizer: reported 1 warnings
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment