hbnl8g
Last Updated: February 25, 2016
·
1.484K
· alexanderbrevig
Feb007acc38e70d57f7b4c205f7e8b26

Protothreads; multitask on a single thread

With protothreads, you split up your long going task into several steps. This may be searching the next level in a tree instead of the whole subtree, or processing of a message queue, garbage collection or whatever.

The basic idea is that you keep track of the last time you executed what you want, and continuously check against the current time to see if it's time do do some more work.

Here is some c style code which presumes that variables are edclared and initialized and that a function called currentTime exists which gives continuous relative indication of time (such as the number of milliseconds since the program started):

if (currentTime() - previous1 >= interval1)
{
  previous1 = currentTime();
  // do something for task 1
}

if (currentTime() - previous2 >= interval2)
{
  previous2 = currentTime();
  // do something for task 2
}

This logic can of course be encapsulated by a class, much like I've done for the http://wiring.org.co/ project here https://github.com/WiringProject/Wiring/blob/master/framework/libraries/TimedAction/TimedAction.cpp.

NB: The accuracy and resolution of currentTime() will be a restrictive factor in what you can do.

Say Thanks
Respond

2 Responses
Add your response

5931
54e2ad6fd33097654a99a61818f61e0a

What happens if I change the time of the system clock at any moment between those steps?

over 1 year ago ·
5953
Feb007acc38e70d57f7b4c205f7e8b26

@herson well, then you probably would not use the system time for the currentTime() function - but indeed you found a potential weakness.
The code suggested here would wait time equal to the negative change, so if you set the system clock back 3 hours (-3) then it would take 3 hours before the protothread started up again. Setting the clock ahead of time would simply cause the thread to run sooner than it originally was supposed to.

over 1 year ago ·