QSemaphore's release() does not immediately notify waiters?
-
I've written a Qt console application to try out QSemaphores and noticed some strange behavior. Consider a semaphore with 1 resource and two threads getting and releasing a single resource. Pseudocode:
@QSemaphore sem(1); // init with 1 resource available
thread1()
{
while(1)
{
if ( !sem.tryAquire(1 resource, 1 second timeout) )
print "thread1 couldn't get a resource";
else
sem.release(1);
}
}// basically the same thing
thread2()
{
while(1)
{
if ( !sem.tryAquire(1 resource, 1 second timeout) )
print "thread2 couldn't get a resource";
else
sem.release(1);
}
}@Seems straightforward, but the threads will often fail to get a resource. A way to fix this is to put the thread to sleep for a bit after sem.release(1). What this tells me is that the release() member does not allow other threads waiting in tryAquire() access to the semaphore before the current thread loops around to the top of while(1) and grabs the resource again.
This surprises me because similar testing with QMutex showed proper behavior... i.e. another thread hanging out in QMutex::tryLock(timeout) gets notified properly when QMutex::unlock() is called.
Any ideas?
-
The fact that a semaphore is released, doesn't mean the waiters can immediately get back to work. The threads are waiting for the semaphore, but also need to get processing time. The thread that releases the semaphore is still running, and still has processing time left, so it can aquire the resource again. If you tell the thread to go to sleep, it will be suspended for a period of time and other threads can start working.
If you would do some more considerable work after releasing the semaphore, you'll notice that other threads do get the resource.
-
Thanks for your reply. This is interesting behavior and I'm glad I now know it. I assumed that releasing a resource like a semaphore or mutex would immediately look for waiting threads and perform a context switch to grant them the resource in place. Instead, it looks like OS scheduling continues as normal. I'm sure a lot of this is OS-dependent, but it's good to know that some behave like this. also: "link":http://stackoverflow.com/questions/8003305/qt-qsemaphores-release-does-not-immediately-notify-waiters