Home | History | Annotate | Download | only in tests
      1 // Test whether no race conditions are reported on std::thread. Note: since
      2 // the implementation of std::thread uses the shared pointer implementation,
      3 // that implementation has to be annotated in order to avoid false positives.
      4 // See also http://gcc.gnu.org/onlinedocs/libstdc++/manual/debug.html for more
      5 // information.
      6 
      7 #include "../../drd/drd.h"
      8 #define _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(addr) \
      9   ANNOTATE_HAPPENS_BEFORE(addr)
     10 #define _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(addr) \
     11   ANNOTATE_HAPPENS_AFTER(addr)
     12 
     13 #include <iostream>
     14 #include <thread>
     15 #include <unistd.h>
     16 
     17 static int i;
     18 
     19 int main(int argc, char** argv)
     20 {
     21   std::thread t1( []() { sleep(1); i = 1; } );
     22   std::thread t2( []() { i = 2; } );
     23   t2.join();
     24   t1.join();
     25   std::cerr << "Done.\n";
     26   return 0;
     27 }
     28 
     29 //
     30 // From libstdc++-v3/src/c++11/thread.cc
     31 //
     32 
     33 extern "C" void* execute_native_thread_routine(void* __p)
     34 {
     35   std::thread::_Impl_base* __t = static_cast<std::thread::_Impl_base*>(__p);
     36   std::thread::__shared_base_type __local;
     37   __local.swap(__t->_M_this_ptr);
     38 
     39   __try {
     40     __t->_M_run();
     41   } __catch(const __cxxabiv1::__forced_unwind&) {
     42     __throw_exception_again;
     43   } __catch(...) {
     44     std::terminate();
     45   }
     46 
     47   return 0;
     48 }
     49 
     50 #include <system_error>
     51 
     52 namespace std
     53 {
     54   void thread::_M_start_thread(__shared_base_type __b)
     55   {
     56     if (!__gthread_active_p())
     57 #if __EXCEPTIONS
     58       throw system_error(make_error_code(errc::operation_not_permitted),
     59                          "Enable multithreading to use std::thread");
     60 #else
     61       __throw_system_error(int(errc::operation_not_permitted));
     62 #endif
     63 
     64     __b->_M_this_ptr = __b;
     65     int __e = __gthread_create(&_M_id._M_thread, execute_native_thread_routine,
     66                                __b.get());
     67     if (__e) {
     68       __b->_M_this_ptr.reset();
     69       __throw_system_error(__e);
     70     }
     71   }
     72 }
     73