views:

43

answers:

3

How can I get an idle thread to be activated again such that its context is restored and execution continued (like if I want a thread to activate after 10 seconds and then be activated after every 5 seconds, in the mean time other threads may continue running)?

+1  A: 

Can't you just have the thread sleep for the required time? Context is inherently part of the thread, so will automatically be restored.

pdbartlett
Isn't there any other way to do it?
interrupted
@interrupted - There are. E.g. you can use a waitable timer and make your thread wait on it. However, from your question it is totally unclear why a simple sleep() won't suffice. You need to be more clear if you want to get any useful answers.
atzz
A: 

How can I get an idle thread to be activated again such that its context is restored and execution continued (like if I want a thread to activate after 10 seconds and then be activated after every 5 seconds, in the mean time other threads may continue running)?

That depends on your threading model: are you using windows threads? boost threads? pthreads? XPCOM threads? something else?

In Windows, you can suspend threads and activate them again.

In boost/pthreads you have to either:

  • start a thread every five seconds, then let it run and die (and start another after five seconds)

  • or have it already running and either tell it "you are now active" from outside (by calling a function on a timer for example)

  • or have it sleep the five seconds, then process, then go to sleep again

From what I've seen in practice the second and third options are the most usual ones. The first one's a bit wasteful as creating threads can be a bit expensive (depending on your platform).

What are you trying to do?

utnapistim
A: 

Depending on the threading API you use, there should be forms of signals to send between threads and a way to wait for such a signal.

Based on that, when a thread is finished, you have it wait for a signal (effectively being asleep and not using any CPU). Some other thread can then store a work item somewhere and signal the sleeping thread to wake up. The woken thread checks for a work item being available, processes that, and goes back waiting for the next item to be signaled.

This is a very simplified version of the approach. (For starters, what if the next work item is stored before the previous was finished?) The exact implementation depends a lot on the API you're using. Try to find a few consumer-producer scenarios for that API, this should give you enough input to chew on.

sbi