Home > database >  linux unnamed posix semaphore sem_destroy, sem_wait method question
linux unnamed posix semaphore sem_destroy, sem_wait method question

Time:06-17

when there are waiting semaphores of sem_wait method, I call the sem_destroy method on other thread. But waiting semaphore was not wake up.

In case of mutex, pthread_mutex_destroy was return the value EBUSY when there are some waiting threads. however sem_destroy return 0 and errno was also set 0.

I want to destroy semaphore after calling sem_destroy to block access as destroyed semaphore and to wake up the waiting thread.

Semaphore handle of Window OS is possible. please advise me. thank you.

CodePudding user response:

POSIX says this about sem_destroy:

The effect of destroying a semaphore upon which other threads are currently blocked is undefined.

It specifically doesn't say that other threads are woken up. In fact, if sem_t contains a pointer to memory, what it almost certainly does do is free the memory, meaning you then have a use-after-free security problem. (Whether that is the case depends on your libc.)

The general approach of allocation for mutexes and semaphores is that they should be either allocated and freed with their relevant data structure, or they should be allocated before the relevant code needs them and then freed after the entire code is done with them. In C, you cannot safely deallocate data structures (e.g., with sem_destroy) that are in use.

If you want to wake up all users of the semaphore, you must increment it until all users have awoken. You can call sem_getvalue to determine if anyone is waiting on the semaphore and then call sem_post to increment it. Only then can you safely destroy it. Note that this can have a race condition, depending on your code.

However, note that you must be careful that the other code does not continue to use the semaphore after it's destroyed, such as by trying to re-acquire it in a loop. If you are careful to structure your code properly, then you can have confidence that this won't happen.

  • Related