Woohoo it's working now!
Warning - probably the ugliest code you've seen in a very long time.
This is an implementation of cooperative "multitasking" using just switch statements and macros. Why? Piece of Mind » Blog Archive » Primitive Multi-Tasking Using Switch Statement - "Have you moo-ed today?"
Code:
#define RESTARTABLE_BEGIN static int restartable_stage = 0; switch(restartable_stage) { case 0:
#define RESTARTABLE_YIELD restartable_stage = __LINE__; return false; case __LINE__:
#define RESTARTABLE_END } restartable_stage = 0; return true;
Example:
Code:
#include <iostream>
bool task1()
{
RESTARTABLE_BEGIN;
std::cout << "t1 -> 1" << std::endl;
RESTARTABLE_YIELD;
std::cout << "t1 -> 2" << std::endl;
RESTARTABLE_YIELD;
std::cout << "t1 -> 3" << std::endl;
RESTARTABLE_END;
}
bool task2()
{
RESTARTABLE_BEGIN;
std::cout << "t2 -> 1" << std::endl;
RESTARTABLE_YIELD;
std::cout << "t2 -> 2" << std::endl;
RESTARTABLE_YIELD;
std::cout << "t2 -> 3" << std::endl;
RESTARTABLE_YIELD;
std::cout << "t2 -> 4" << std::endl;
RESTARTABLE_YIELD;
std::cout << "t2 -> 5" << std::endl;
RESTARTABLE_END;
}
int main(int argc, char* argv[])
{
bool task1_done = false;
bool task2_done = false;
while (!(task1_done && task2_done))
{
if (!task1_done)
{
task1_done = task1();
}
if (!task2_done)
{
task2_done = task2();
}
}
return 0;
}
May be useful in embedded applications if your requirements are simple and can't be bothered to get a real scheduler.
This program actually triggers a bug in VS2010. It doesn't like __LINE__ as a case label (saying it's not constant) if edit and continue debugging is turned on.
Workaround provided by putty -
337 * In particular, if you are getting `case expression not constant'
338 * errors when building with MS Visual Studio, this is because MS's
339 * Edit and Continue debugging feature causes their compiler to
340 * violate ANSI C. To disable Edit and Continue debugging:
341 *
342 * - right-click ssh.c in the FileView
343 * - click Settings
344 * - select the C/C++ tab and the General category
345 * - under `Debug info:', select anything _other_ than `Program
346 * Database for Edit and Continue'.
347 */