Untitled
unknown
plain_text
4 years ago
2.5 kB
6
Indexable
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <semaphore.h>
int teamACount=0;
int teamBCount=0;
sem_t s;
pthread_barrier_t barrier;
void *function(void *argum)
{
char* args = (char *) argum;
char teamName = *args;
sem_wait(&s);
if (teamName == 'A')
{
if ( !((teamACount ==2 && teamBCount == 2) || (teamACount ==4) || (teamBCount ==4)) )
{
teamACount++;
printf("A count: %d\n", teamACount);
printf("Thread ID: %ld , Team: %c, I am currently looking for a car\n", pthread_self(), teamName);
}
else{
pthread_barrier_wait(&barrier);
}
}
else if (teamName == 'B')
{
if ( (!((teamACount ==2 && teamBCount == 2) || (teamACount ==4) || (teamBCount ==4)) )
{
teamBCount++;
printf("B count: %d\n", teamBCount);
printf("Thread ID: %ld , Team: %c, I am currently looking for a car\n", pthread_self(), teamName);
}
else{
pthread_barrier_wait(&barrier);
}
}
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);
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...