Subj : Re: Tjme out in lock To : comp.programming.threads From : loic-dev Date : Wed Apr 06 2005 09:43 am Hi Alex, > Ithought something like this (acquire for at most n secs) > > Enter critical section > if sem is not acquired > acquire > else > wait(n secs) > if sem is not acquired > acquire > else > TIMEOUT > Exit critical section What you want to do is to wait at most n secs to acquire the sema, correct? > Ideally all threads should do the waiting concurrently, and > then try to get the semaphore, but I'm not sure is possible? Why not? This depends actually on your wait semantic. If you mean something similar to nanosleep(), then yes the thread shall wait concurrently. > And one other problem is that if the semaphore is released while waiting, > the thread will be waiting till the end of the timeout. > Maybe a signal should be added or maybe do busy wait? That's correct. One solution consists to do busy waiting, perhaps k loops that waits n/k secs in order to improve the response time. But that solution is not really terrific... The second (better) solution is to wake up from the wait() function as soon as the thread release the sema. This might involve the use of signal(s) in order to interrupt the wait() call. IIRC, LinuxThreads implemented conditions variables based on such signal mechanism. Of course, if several threads are contending for the same semaphore, you'll get the (classical) effect that most of them shall be awaken to find the semaphore already acquired. Leading to unnecessary context switch. > Keep in mind I do this to learn. I know there already is support in > pthreads, but I'm trying to understand and see it for myself. Hope this help! Cheers, Loic. .