-
Does a QSemaphore need to be released before deletion?
-
If yes, I should call
semaphore->release(n)beforedelete semaphore, but how do I know how many (n) resources are acquired? (I know how many resources areavailable(), but not the overall “size” of the semaphore.)
Reason for my question: I’m hunting down memory leaks and found a QSemaphore that created a memory leak although delete was (seems to have been) called on it. Maybe that happened because it was not released correctly – The doc says “Warning: Destroying a semaphore that is in use may result in undefined behavior.“
Edit: The memory leak actually was the result of a memory dump function placed before all objects were destroyed. Adding an extra scope { ... } helped there. Nevertheless, my question remains.
I do not think you need to release a semaphore before destruction, as
release()just adds a specified number of resources (aka permits) to the semaphore. If you look at the examples for QSemaphore, you can find thatrelease()can increase the number of available permits beyond the initial amount.What the doc says is that no thread should operate with the semaphore that is being destroyed. In other words, all threads should complete their calls of the semaphore object methods, whatever those are, before it can be safely destroyed. And the class itself has no support for this; it’s solely application responsibility to ensure that, by external means. Actually, it’s a common situation in multi-threaded programming that destruction of an object (even a synchronization object) that is still in use is unsafe.