What may happen if I don't destroy a semaphore? [closed]

大兔子大兔子 提交于 2019-12-01 12:14:04

It is operating system specific. On Linux, read sem_overview(7); actually you are in an unspecified case. However, the documentation says

Before being used, an unnamed semaphore must be initialized using sem_init(3). It can then be operated on using sem_post(3) and sem_wait(3). When the semaphore is no longer required, and before the memory in which it is located is deallocated, the semaphore should be destroyed using sem_destroy(3).

so you should call sem_destroy when appropriate; don't risk having a system-wide resource leak. BTW documentation of sem_destroy(3) tells:

An unnamed semaphore should be destroyed with sem_destroy() before the memory in which it is located is deallocated. Failure to do this can result in resource leaks on some implementations.

For named semaphores, things are different (they sit in /dev/shm/). I guess that a thread-shared semaphore might be destroyed when its memory segment is removed (no more mapped by any process). I am not sure of this and it is implementation specific behavior, so don't rely on this.

Use also proc(5).

So what may happen is a system-wide resource leak and you don't want it. You might need to reboot to remove it. BTW, you could use strace(1) to find out the actual syscalls involved, and you could look into the source code of your GNU glibc (or some other libc, like musl-libc) - and perhaps of the Linux kernel- to understand more the implementation specific behavior.

Avoid undefined behavior.

The address where Semaphore is stored will hold the last value of the semaphore if you dont use sem_destroy ...

It might cause problems as the semaphore's previous value might be indicating that a process is still running even if it is not !

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!