Guest User

Untitled

a guest
Oct 18th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. #include <iostream>
  2. #include <unistd.h>
  3. #include <thread>
  4. #include <vector>
  5. #include <signal.h>
  6. #include <semaphore.h>
  7.  
  8. using namespace std;
  9.  
  10. vector<thread*> th;
  11. static sem_t semaphore;
  12.  
  13. void quit(int q)
  14. {
  15. cout << "End" << endl;
  16. exit(0);
  17. }
  18.  
  19. void event(int index)
  20. {
  21. while(1)
  22. {
  23. static long count = 0;
  24. sem_wait(&semaphore);
  25. cout << "Thread:" << index << " Count:" << count << endl;
  26. count++;
  27. sem_post(&semaphore);
  28. usleep(10000);
  29. }
  30. }
  31.  
  32. int main(int argc, char ** argv)
  33. {
  34. if(argc<2)
  35. {
  36. cerr << "Error: num-thread" << endl;
  37. exit(0);
  38. }
  39. int MAX_THREAD=atoi(argv[1]);
  40. signal(SIGINT,quit);
  41. if (sem_init(&semaphore, 0, 1) == -1)
  42. cerr << "Error: semaphore" << endl;
  43. for(int i = 0; i < MAX_THREAD; i++)
  44. {
  45. thread* t = new thread(event, i);
  46. th.push_back(t);
  47. }
  48. for(int i = 0; i < th.size(); i++)
  49. th[i]->join();
  50. return 0;
  51. }
Add Comment
Please, Sign In to add comment