fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <iostream>
  4. #include <vector>
  5. #include <pthread.h>
  6.  
  7. using namespace std;
  8.  
  9. #define MAX_TD_NUM 2 //設定thread數
  10.  
  11. vector<int> all_ok_or_not;
  12. pthread_t tid[MAX_TD_NUM];
  13. int para[MAX_TD_NUM];
  14.  
  15. int check_all_ok(int *step);
  16. void *thread(void *arg);
  17.  
  18. pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
  19. pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
  20.  
  21. int main (){
  22. int i,j;
  23.  
  24. for(i=0;i<MAX_TD_NUM;i++){
  25. all_ok_or_not.push_back(-1);
  26. para[i]=i;
  27. }
  28.  
  29. for(i=0;i<MAX_TD_NUM;i++)
  30. pthread_create(&tid[i], NULL, thread,&para[i]);
  31.  
  32. for(i=0;i<MAX_TD_NUM;i++)
  33. pthread_join(tid[i], NULL);
  34.  
  35. return 0;
  36. }
  37.  
  38. void *thread(void *arg){
  39. int tid=*(int *)arg;
  40. int step=0;
  41.  
  42. while(step<1000){
  43.  
  44. step++; //假設工作完成 step++
  45.  
  46.  
  47. pthread_mutex_lock(&lock);
  48. all_ok_or_not[tid]=step; //把我id的那格設成0 代表我完成工作
  49. pthread_mutex_unlock(&lock);
  50.  
  51. while(check_all_ok(&step) == 0){//若有thread未完成 則一直檢查
  52.  
  53. }
  54.  
  55.  
  56.  
  57. }
  58.  
  59.  
  60.  
  61. }
  62.  
  63. int check_all_ok(int *step){ //檢查是否每個thread都做完了 是回傳1 否則0
  64. int i;
  65.  
  66. for(i=0;i<MAX_TD_NUM;i++){
  67. pthread_mutex_lock(&lock);
  68. if(*step!=all_ok_or_not[i]){
  69. pthread_mutex_unlock(&lock);
  70. return 0;
  71. }
  72. pthread_mutex_unlock(&lock);
  73. }
  74. return 1;
  75. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main()’:
prog.cpp:22: warning: unused variable ‘j’
prog.cpp: In function ‘void* thread(void*)’:
prog.cpp:61: warning: control reaches end of non-void function
/home/Hh9XzO/ccr6pITU.o: In function `main':
prog.cpp:(.text+0x1c5): undefined reference to `pthread_create'
prog.cpp:(.text+0x1e9): undefined reference to `pthread_create'
prog.cpp:(.text+0x1fe): undefined reference to `pthread_join'
prog.cpp:(.text+0x213): undefined reference to `pthread_join'
collect2: ld returned 1 exit status
stdout
Standard output is empty