Advertisement
Guest User

Untitled

a guest
May 16th, 2014
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. #include <windows.h>
  2. #include <thread>
  3. #include <atomic>
  4.  
  5. #define THREADCOUNT 4
  6.  
  7. std::thread Threads[THREADCOUNT];
  8. HANDLE TestEvent;
  9.  
  10. std::atomic<int> ThreadCounter = 0;
  11.  
  12. void WaitForAllThreads()
  13. {
  14.     if (ThreadCounter.fetch_add(1) == THREADCOUNT - 1)
  15.     {
  16.         ThreadCounter = 0;
  17.         SetEvent(TestEvent);
  18.         ResetEvent(TestEvent);
  19.     }
  20.     else
  21.         WaitForSingleObject(TestEvent, INFINITE);
  22. }
  23.  
  24. bool Run = true;
  25.  
  26. void ThreadFunction()
  27. {
  28.     while (Run)
  29.     {
  30.         printf("work 000\n");
  31.         WaitForAllThreads();
  32.         printf("work 111\n");
  33.         WaitForAllThreads();
  34.     }
  35. }
  36.  
  37. int main()
  38. {
  39.     TestEvent = CreateEvent(
  40.         NULL,               // default security attributes
  41.         TRUE,               // manual-reset event
  42.         FALSE,              // initial state is nonsignaled
  43.         TEXT("TestEvent")  // object name
  44.         );
  45.  
  46.     for (int i = 0; i < THREADCOUNT; ++i)
  47.         Threads[i] = std::thread(&ThreadFunction);
  48.  
  49.     getchar();
  50.     bool Run = false;
  51.  
  52.     for (int i = 0; i < THREADCOUNT; ++i)
  53.         Threads[i].join();
  54.  
  55.     getchar();
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement