Guest User

Untitled

a guest
Apr 22nd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. // -*- coding:utf-8 -*-
  2. // author:phenix3443
  3. // desc: 屏障(barrier)使用示例
  4.  
  5.  
  6. #include <iostream>
  7. #include <pthread.h>
  8. #include <unistd.h>
  9. #include <vector>
  10. #include <cstdlib>
  11.  
  12. void *first_work(void *arg) {
  13. pthread_barrier_t *b = static_cast<pthread_barrier_t *>(arg);
  14. unsigned int i = rand() % 1000 + 100;
  15. std::cout << pthread_self() << " sleep " << i << "microseconds" << std::endl;
  16. usleep(i);
  17. int res = pthread_barrier_wait(b);
  18. if (res == PTHREAD_BARRIER_SERIAL_THREAD) {
  19. std::cout << pthread_self() << " all thread done first work!" << std::endl;
  20. }
  21. return ((void*)0);
  22. }
  23.  
  24. int main(int argc, char *argv[])
  25. {
  26. const int thread_num = 10;
  27. pthread_barrier_t b;
  28. pthread_barrier_init(&b, NULL, thread_num);
  29. std::vector<pthread_t> tids(thread_num);
  30. for(auto &tid : tids) {
  31. if(pthread_create(&tid, NULL, first_work, (void*)&b)) {
  32. std::cout << "create thread error" << std::endl;
  33. return 1;
  34. }
  35. }
  36.  
  37. for(auto &tid : tids) {
  38. pthread_join(tid, NULL);
  39. }
  40. pthread_barrier_destroy(&b);
  41. return 0;
  42. }
Add Comment
Please, Sign In to add comment