Advertisement
Omnifarious

Simple use of C++11 thread support

Dec 6th, 2012
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. #define _GLIBCXX_USE_NANOSLEEP 1
  2. #include <thread>
  3. #include <condition_variable>
  4. #include <iostream>
  5. #include <unistd.h>
  6.  
  7. void runthread(::std::mutex &m, ::std::condition_variable &v, bool &started)
  8. {
  9.    ::std::this_thread::sleep_for(::std::chrono::milliseconds(500));
  10.    {
  11.       ::std::unique_lock< ::std::mutex> lock(m);
  12.       started = true;
  13.       v.notify_one();
  14.    }
  15.    ::std::cerr << "I am the new thread!\n";
  16. }
  17.  
  18. int main()
  19. {
  20.    ::std::mutex m;
  21.    ::std::condition_variable v;
  22.    bool started = false;
  23.    ::std::thread newthread(runthread, ::std::ref(m), ::std::ref(v), ::std::ref(started));
  24.    {
  25.       ::std::unique_lock< ::std::mutex> lock(m);
  26.       while (!started) {
  27.          v.wait(lock);
  28.       }
  29.    }
  30.    ::std::cerr << "Both I and the new thread are running.\n";
  31.    newthread.join();
  32.    return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement