Guest User

Untitled

a guest
Jan 24th, 2013
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <iostream>
  4. #include <queue>
  5. #include <time.h>
  6. #include <vector>
  7. #include <map>
  8. #include <algorithm>
  9. #include <bitset>
  10. #include <pthread.h>
  11. #include <pthread.h>
  12.  
  13. #define MAX_TD_NUM 5 //THREADF數量
  14.  
  15. using namespace std;
  16.  
  17. void *fun(void *arg);
  18.  
  19. pthread_t tid[MAX_TD_NUM];
  20. int para[MAX_TD_NUM];
  21.  
  22. int round_flag[MAX_TD_NUM];
  23.  
  24. int main (){
  25.     int i,j;
  26.    
  27.     for(i=0;i<MAX_TD_NUM;i++)//初始化 round_flag 都給-1
  28.         round_flag[i]=-1;
  29.        
  30.     for(i=0;i<MAX_TD_NUM;i++){
  31.         para[i]=i;
  32.         pthread_create(&tid[i], NULL, fun, &para[i]);
  33.     }
  34.    
  35.     for(i=0;i<MAX_TD_NUM;i++)
  36.         pthread_join(tid[i], NULL);
  37.    
  38.    
  39.     return 0;
  40. }
  41.  
  42. void *fun(void *arg){
  43.     int pn=*(int *)arg;
  44.     int i;
  45.     int lock_off=0;
  46.     int roundallok=0;
  47.    
  48.     while(lock_off < 10){
  49.                    
  50.         // 固定點同步A
  51.         round_flag[pn]=lock_off;//把ID對應的round_flag填入lock_off
  52.         while(roundallok==0){            
  53.             roundallok=1;                  
  54.             for(i=0;i<MAX_TD_NUM;i++){//確認其他人是否都做到這裡
  55.                 if( (round_flag[i]!= lock_off) && (round_flag[i]!= (lock_off+1)) ){
  56.                     roundallok=0;//若有人還沒到  roundallok給0 讓他繼續卡迴圈
  57.                 }
  58.             }
  59.         }
  60.         roundallok=0;
  61.         lock_off++;//通過後計步器+1
  62.         //
  63.        
  64.         cout<<pn<<"\n";//通過後做自己的工作
  65.        
  66.         // 固定點同步B  同A
  67.         round_flag[pn]=lock_off;
  68.         while(roundallok==0){            
  69.             roundallok=1;                  
  70.             for(i=0;i<MAX_TD_NUM;i++){
  71.                 if( (round_flag[i]!= lock_off) && (round_flag[i]!= (lock_off+1)) ){
  72.                     roundallok=0;
  73.                 }
  74.             }
  75.         }
  76.         roundallok=0;
  77.         lock_off++;        
  78.         //
  79.          
  80.         cout<<pn<<"\n";
  81.        
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment