Advertisement
Guest User

Threads in C++11

a guest
Nov 4th, 2014
910
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <mutex>
  4. #include <thread>
  5.  
  6. using std::cout;
  7. using std::endl;
  8. using std::thread;
  9.  
  10. void threadsleep(int millisecs)
  11. {
  12.   std::timed_mutex m;
  13.   m.lock();
  14.   m.try_lock_for(std::chrono::milliseconds(millisecs));
  15. }
  16.  
  17.  
  18. class test
  19. {
  20. public:
  21.   test() { }
  22.   void start() {
  23.     t1 = thread(&test::run1, this);
  24.     t2 = thread(&test::run2, this);
  25.   }
  26.   void stop() {
  27.     t1.join();
  28.     t2.join();
  29.   }
  30. private:
  31.   void run1() {
  32.     for (int i=0; i<100; i++) {
  33.       cout << "Run 1 ";
  34.       threadsleep(100);
  35.     }
  36.     cout << endl;
  37.   }
  38.   void run2() {
  39.     for (int i=0; i<100; i++) {
  40.       cout << "Run 2 ";
  41.       threadsleep(100);
  42.     }
  43.     cout << endl;
  44.   }
  45.   thread t1, t2;
  46. };
  47.  
  48.  
  49. int main()
  50. {
  51.   test tt;
  52.   cout << "Start..." << endl;
  53.   tt.start();
  54.   threadsleep(1000);
  55.   tt.stop();
  56.   cout << "Done..." << endl;
  57.   return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement