'semaphore is not getting accessed eventhough it is unlocked

I have written a 2 programs in order to understand how to implement semaphores.

Give.c: Creates a semaphore with initial value of 1 and unlocks it

    /*
* Brief - This program is used to create a semaphore and "unlock" it
* 
* 
*
* Reference - https://unix.stackexchange.com/questions/651965/how-to-open-an-existing-named-semaphore 
*/
#include <stdio.h> 
#include <pthread.h> 
#include <unistd.h> 
#include <semaphore.h> 
#include <fcntl.h>
#include <sys/stat.h>

sem_t *semaphore;

int ret=1; 

//Thread function
void *threadFunc(void *data)
{
    
    sem_post(semaphore);

    printf("Thread:Completed execution!\n");

    pthread_exit(&ret);
}


int main()
{
    semaphore = sem_open("semaphore",O_CREAT,0644,1);

    sleep(5);

    pthread_t task; 

    pthread_create(&task,NULL,threadFunc,NULL);

    

    printf("Main: Waiting for thread to complete!\n");
    pthread_join(task,NULL);
    printf("Main: Exiting now!\n");

    return 0;

}

Take.c: Opens a semaphore and tries to access it. But, has to wait until it is released by Give.c

/*
* Brief - This program is used to open a semaphore and "read" or "lock" it.
*       - However, it has to wait until the semaphore has been unlocked by "Give.c"
* 
* 
*
* Reference - https://unix.stackexchange.com/questions/651965/how-to-open-an-existing-named-semaphore 
*/
#include <stdio.h> 
#include <pthread.h> 
#include <unistd.h> 
#include <semaphore.h> 

sem_t *semaphore;

int ret=1; 

//Thread function
void *threadFunc(void *data)
{

    printf("Thread: Waiting for semaphore to be unlocked\n");
    sem_wait(semaphore);

    printf("Thread:Completed execution!\n");

    pthread_exit(&ret);
}


int main()
{

    pthread_t task; 

    semaphore = sem_open("semaphore",0);

    pthread_create(&task,NULL,threadFunc,NULL);

    sleep(5);

    printf("Main: Waiting for thread to complete!\n");
    pthread_join(task,NULL);
    printf("Main: Exiting now!\n");

    return 0;

}

First, I execute give.c which creates and initializes the semaphore with the value of 1. Within 5 seconds (NOTE: give.c sleeps for 5 seconds), I run Take.c. However, it still waits for Give.c to unlock the semaphore. Why is this happening? The initial value being 1, should already unlock the semaphore right? My expectation from this was that Take.c should not wait for semaphore to be released as it is initialized with 1.

Please share your thoughts. Thanks in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source