I am trying to use semaphores but they are not working in the terminal for some reason.
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
sem_t mySem;
void *p1a(void *arg)
{
sem_wait(&mySem);
printf("B");
return NULL;
}
void *p2a(void *arg){
printf("A");
sem_post(&mySem);
return NULL;
}
int main(void)
{
sem_init(&mySem, 0, 0);
pthread_t p1;
pthread_t p2;
if (pthread_create(&p1, NULL, p1a, NULL))
{
printf("Error creating thread.\n");
exit(1);
}
sleep(2);
if (pthread_create(&p2, NULL, p2a, NULL))
{
printf("Error creating thread.\n");
exit(1);
}
pthread_join(p1,NULL);
pthread_join(p2,NULL);
sem_destroy(&mySem);
exit(0);
}
The result I get is BA but when I ran the same code in replit, it printed AB. Im not sure why this is happening and any help would be appreciated.