问题
Is there any way by which I can know the number of processes or threads waiting on a particular semaphore? Like a API to check the value. Sem_getvalue() only returns 0 and not a negative number whose absolute value is the number of tasks blocking on the semaphore as mentioned on a few sites.
Any help would be great.
Thanks in advance!!
回答1:
There is no way to do this in the POSIX API other than sem_getvalue
, which semantics, as you have seen, are optional.
That said, Linux implements named POSIX semaphores as files under /dev/shm
, and thus a utility like fuser(1) can show you which processs have the file open.
If that doesn't work for you, you could implement a bookkeeping semaphore yourself with a POSIX mutex, a POSIX condition variable, and some space to record the semaphore value and any waiters.
回答2:
I really have acquired a dislike for POSIX semaphores. They lack a lot of the functionality available with SYS V semaphores.
If you are using SYS V semaphores, you can get various information using the semctl function:
int semctl(int semid, int semnum, int cmd, ...);
For example, to get the number of processed awaiting the defined semaphore to become zero:
int cnt = semtcl(my_semid, 0, GETZCNT);
That simple!
Long live SYS V semaphores!
回答3:
May be you could have taken a global atomic_t variable and incremented it before calling sem_wait and decremented in case you get the semaphore.
来源:https://stackoverflow.com/questions/17844348/find-number-of-tasks-blocking-on-a-posix-semaphore