Why does semaphore not affected by post from different thread?

Semaphore is defined as static variable

static int semaphore = -1;

I am trying to post to this semaphore

sem_post(&semaphore);

There is a wait for semaphore in the thread created this way:

pthread_create(&tid, NULL, start, NULL);

and

static void *start(void *context)
{
    // ...

    sem_init(&semaphore, 0, 0);    
    sem_wait(&semaphore);

    // ...

    return NULL;
}

Somehow wait for semaphore is not affected by semaphore post. If I post for semaphore from start routine everything is ok.

What is the problem?

Upvotes: 2

Views: 463

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Passing int* instead of sem_t* as the first parameter of sem_xxx functions may access memory past the allocated region. According to at least one source of <semaphore.h>, the size of sem_t is 16 to 32 bytes; int is not going to be sufficient to hold the structure of a semaphore, potentially resulting in undefined behavior.

You need to change

static int semaphore = -1;

to

static sem_t semaphore;

to fix the access past the allocated memory region.

Also, it is generally a good idea to initialize your semaphores before starting the threads that use them. You should move the initialization call from the start() function to the main(), or whatever function that you use to start your thread.

sem_init(&semaphore, 0, 0);

Upvotes: 4

Related Questions