1

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.

jotaro
  • 53
  • 4
  • I just ran your code on my machine with gcc (Ubuntu 4.8.4-2ubuntu1~14.04.4) 4.8.4 and got AB as result. – Leonardo Araujo Nov 17 '21 at 23:43
  • [I got AB as expected](https://godbolt.org/z/59rrsGv3f) – ikegami Nov 17 '21 at 23:45
  • The only way I can see BA being printed is if each thread has its own buffer for stdout, and they get flushed in the wrong order. This would be fixed by explicitly flushing them. – ikegami Nov 17 '21 at 23:46
  • I wonder why its not working for me in the terminal. I'm compiling it with gcc -pthread – jotaro Nov 17 '21 at 23:46
  • Can you send the output of gcc --version? – Leonardo Araujo Nov 17 '21 at 23:47
  • 1
    This is the output of gcc --version Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/c++/4.2.1 Apple clang version 12.0.0 (clang-1200.0.32.29) Target: x86_64-apple-darwin19.6.0 Thread model: posix InstalledDir: /Library/Developer/CommandLineTools/usr/bin – jotaro Nov 17 '21 at 23:48
  • Check for `gcc --version -v`, it outputs more information – Leonardo Araujo Nov 17 '21 at 23:50
  • @LeonardoAraujo its showing the same information – jotaro Nov 17 '21 at 23:52
  • works fine https://godbolt.org/z/jKqY7x3bd If it does not work semaphores would be rather useless. – 0___________ Nov 17 '21 at 23:53

0 Answers0