Untitled
unknown
plain_text
3 years ago
2.3 kB
3
Indexable
#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> #include <semaphore.h> #define MAX_PASSENGER 4 int countA = 0; int countB = 0; int totalCount = 0; sem_t sem; pthread_barrier_t barrier; pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER; void * rideShare(void *argv) { char *args = (char*)argv; char team = *args; while(totalCount <MAX_PASSENGER) { if(team == 'A') { if((countA == 2 && countB == 2) || (countA == 4 || countB == 4)) { printf("Thread ID: %ld , Team: %c, I have found a spot on the car\n", pthread_self(), teamName); totalCount++; } else{ printf("Thread ID: %ld , Team: %c, I am currently looking for a car\n", pthread_self(), teamName); countA++; } } else if(team == 'B') { if((countA == 2 && countB == 2) || (countA == 4 || countB == 4)) { printf("Thread ID: %ld , Team: %c, I have found a spot on the car\n", pthread_self(), teamName); totalCount++; } else{ printf("Thread ID: %ld , Team: %c, I am currently looking for a car\n", pthread_self(), teamName); countB++; } } } } int main(int argc, char* argv[]) { pthread_t *thread_A , *thread_B; int sizeA = atoi(argv[1]); int sizeB = atoi(argv[2]); char a='A'; char b='B'; pthread_barrier_init(&barrier, NULL, 4); sem_init(&sem, 0, 1); if(sizeA % 2==0 && sizeB % 2 == 0 && (sizeA + sizeB)%4 == 0) { threadA=(pthread_t *)malloc(sizeA* sizeof(pthread_t )); for(int i=0;i<sizeA;i++) { pthread_create(&thread_A[i],NULL,rideShare,&a); } threadB=(pthread_t *)malloc(sizeB * sizeof(pthread_t )); for( int i=0;i<sizeB;i++) { pthread_create(&thread_B[i],NULL,rideShare,&b); } for(int i=0;i<sizeA;i++) { pthread_join(thread_A[i],NULL); } for(int i=0;i<sizeB;i++) { pthread_join(thread_B[i],NULL); } } printf("The main terminates\n"); return 0; }
Editor is loading...