Untitled
unknown
plain_text
3 years ago
3.0 kB
3
Indexable
#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> #include <semaphore.h> int size; char **board; int row = 0; int col=0; char a = 'X'; int turn =0; char whoWon = '-'; sem_t s; pthread_barrier_t barrier; pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER; void *function(void *argum) { int teamACount=0; int teamBCount=0; char* args = (char *) argum; char teamName = *args; sem_wait(&s); if (teamName == 'A') { //sem_wait(&s); printf("Thread ID: %ld , Team: %c, I am currently looking for a car\n", pthread_self(), teamName); if ( (teamACount ==2 && teamBCount == 2) || (teamACount ==4) || (teamBCount ==4) ) { pthread_barrier_wait(&barrier); printf("Thread ID: %ld , Team: %c, I have found a spot on the car\n", pthread_self(), teamName); } teamACount++; printf("A count: %d\n", teamACount); sem_post(&s); pthread_barrier_wait(&barrier); } else if (teamName == 'B') { printf("Thread ID: %ld , Team: %c, I am currently looking for a car\n", pthread_self(), teamName); if ( (teamACount ==2 && teamBCount == 2) || (teamACount ==4) || (teamBCount ==4) ) { pthread_barrier_wait(&barrier); printf("Thread ID: %ld , Team: %c, I have found a spot on the car\n", pthread_self(), teamName); } teamBCount++; printf("B count: %d\n", teamBCount); sem_post(&s); pthread_barrier_wait(&barrier); } } /* char teamGeneration(){ char team; srand(time(NULL)); int num= rand() % 1; if (num == 0) team = 'A'; else team = 'B'; return team; }*/ int main(int argc, int* argv[]) { pthread_t *threadA, *threadB; int sizeofteamA = atoi(argv[1]); int sizeofteamB = atoi(argv[2]); char a='A'; char b='B'; pthread_barrier_init(&barrier, NULL, 4); //argc = 3 sem_init(&s, 0,1); if (sizeofteamA % 2 == 0 && sizeofteamB % 2 == 0 && (sizeofteamA+sizeofteamB)%4 == 0) { threadA=(pthread_t *)malloc(sizeofteamA* sizeof(pthread_t )); for(int i=0;i<sizeofteamA;i++) { pthread_create(&threadA[i],NULL,function,&a); //Default Attributes } threadB=(pthread_t *)malloc(sizeofteamB * sizeof(pthread_t )); for( int i=0;i<sizeofteamB;i++) { pthread_create(&threadB[i],NULL,function,&b); //Default Attributes } for(int i=0;i<sizeofteamA;i++) { pthread_join(threadA[i],NULL); } for(int i=0;i<sizeofteamB;i++) { pthread_join(threadB[i],NULL); } } else{ printf("The main terminates\n"); } printf("The main terminates\n"); return 0; }
Editor is loading...