Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.5 kB
1
Indexable
Never
#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 mutex, barrier;

void * rideShare(void *argv)
{
    char *args = (char*)argv;
    char team = *args;
    while(totalCount <MAX_PASSENGER)
    {
        if(team == 'A'&& countA != 2 && countA !=4)
        {
            printf("Thread ID: %ld , Team: %c, I am currently looking for a car\n", pthread_self(), team);
            countA++;
        }
        else if(team == 'B' && countB != 2 && countB !=4)
        {
            printf("Thread ID: %ld , Team: %c, I am currently looking for a car\n", pthread_self(), team);
            countB++; 
        }
        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(), team);
            totalCount++;
        }
    }
}
char decideTeam(char &x)
{
    char c;
    srand(time(NULL));
    int num = rand() %2;
    if(num == 0)
    {
        c = 'A';
        x = 'B';
    }
    else
    {
        c = 'B';
        x = 'A'; 
    }
    return c;
}
int main(int argc, char* argv[])
{
    pthread_t *thread_A , *thread_B;
    int sizeA = atoi(argv[1]);
    int sizeB = atoi(argv[2]);
    int size1, size2;
    int barrierSize;
    char char1, char2;
    char1 = decideTeam(char2);
    if(char1 == 'A')
    {size1 = sizeA;
    size2 = sizeB;}
    else if(char1=='B')
    {size1 = sizeB;
    size2 = sizeA;}
    if(sizeA + sizeB == 4);
    {barrierSize = 4}
    else{barrierSize == 5;}
    //match size1 & AorB & char1 and size2 & AorB & char2
    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(size1* sizeof(pthread_t ));
        for(int i=0;i<sizeA;i++)
        {
            pthread_create(&thread_A[i],NULL,rideShare,&char1);
        }

        threadB=(pthread_t *)malloc(size2 * sizeof(pthread_t ));
        for( int i=0;i<sizeB;i++)
        {
            pthread_create(&thread_B[i],NULL,rideShare,&char2);
        }
        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;
}