
Howard Hinnant wrote:
Or are we talking about a worker thread that has been forced to sleep for X amount of time? I.e. part of its task is to sleep. If so, why is that worker thread forced to sleep, and perhaps having it sleep on a condition variable would be better?
Alright, I will add some more context to the discussion. This is being used for a 'timeout lifetime' for the singleton library. The idea is that a singleton which is cheap to create but expensive to hold on to could automatically be destroyed if it goes unused a certain amount of time, and be recreated the next time it is needed. To implement this idea I create a timeout thread when the instance is created, and force that thread to sleep until the timeout time is reached. If at that point the timeout time has been extended, the thread sleeps again, otherwise it destroys the instance and exits. The problem is that if the process is exiting I would like to force the thread to wake up and time out early to ensure that the singleton get destroyed. Anthony Williams wrote:
This sounds like a prime target for the use of a condition variable to me. You can wait on a condition variable, then signal the condition variable to wake the sleeping thread. Yes it means acquiring a lock, but most thread synchronization requires some form of lock.
I am relatively new to threading, so forgive me if my question is naive, but what is the formal definition of a condition variable? If a condition variable is capable of making a thread that has been explicitly told to sleep until a certain time wake up early, can you show me an example of its use? Thanks. -Jason