Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <iostream>
- #include <queue>
- #include <time.h>
- #include <vector>
- #include <map>
- #include <algorithm>
- #include <bitset>
- #include <pthread.h>
- #include <pthread.h>
- #define MAX_TD_NUM 5 //THREADF數量
- using namespace std;
- void *fun(void *arg);
- pthread_t tid[MAX_TD_NUM];
- int para[MAX_TD_NUM];
- int round_flag[MAX_TD_NUM];
- int main (){
- int i,j;
- for(i=0;i<MAX_TD_NUM;i++)//初始化 round_flag 都給-1
- round_flag[i]=-1;
- for(i=0;i<MAX_TD_NUM;i++){
- para[i]=i;
- pthread_create(&tid[i], NULL, fun, ¶[i]);
- }
- for(i=0;i<MAX_TD_NUM;i++)
- pthread_join(tid[i], NULL);
- return 0;
- }
- void *fun(void *arg){
- int pn=*(int *)arg;
- int i;
- int lock_off=0;
- int roundallok=0;
- while(lock_off < 10){
- // 固定點同步A
- round_flag[pn]=lock_off;//把ID對應的round_flag填入lock_off
- while(roundallok==0){
- roundallok=1;
- for(i=0;i<MAX_TD_NUM;i++){//確認其他人是否都做到這裡
- if( (round_flag[i]!= lock_off) && (round_flag[i]!= (lock_off+1)) ){
- roundallok=0;//若有人還沒到 roundallok給0 讓他繼續卡迴圈
- }
- }
- }
- roundallok=0;
- lock_off++;//通過後計步器+1
- //
- cout<<pn<<"\n";//通過後做自己的工作
- // 固定點同步B 同A
- round_flag[pn]=lock_off;
- while(roundallok==0){
- roundallok=1;
- for(i=0;i<MAX_TD_NUM;i++){
- if( (round_flag[i]!= lock_off) && (round_flag[i]!= (lock_off+1)) ){
- roundallok=0;
- }
- }
- }
- roundallok=0;
- lock_off++;
- //
- cout<<pn<<"\n";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment