This class does not perform any magic it only makes calls to makecontext() and swapcontext(). Getting the details right however is complicated and MTasker does that for you.
If preemptive multitasking or more advanced concepts such as semaphores, locks or mutexes are required, the use of POSIX threads is advised.
MTasker is designed to offer the performance of statemachines while maintaining simple thread semantics. It is not a replacement for a full threading system.
This function is now free to do whatever it wants, but realise that MTasker implements cooperative multitasking, which means that the coder has the responsiblilty of not taking the CPU overly long. Other threads can only get the CPU if MTasker::yield() is called or if a thread sleeps to wait for an event, using the MTasker::waitEvent() method.
for(;;) { MT.schedule(); if(MT.noProcesses()) // exit if no processes are left break; }
The kernel typically starts from the main() function of your program. New threads are also created from the kernel. This can also happen before entering the main loop. To start a thread, the method MTasker::makeThread is provided.
An event can be a keypress, but also a UDP packet, or a bit of data from a TCP socket. The sample code provided works with keypresses, but that is just a not very useful example.
A thread can also wait for an event only for a limited time, and receive a timeout of that event did not occur within the specified timeframe.
MTasker<> MT; void menuHandler(void *p) { int num=(int)p; cout<<"Key handler for key "<<num<<" launched"<<endl; MT.waitEvent(num); cout<<"Key "<<num<<" was pressed!"<<endl; } int main() { char line[10]; for(int i=0;i<10;++i) MT.makeThread(menuHandler,(void *)i); for(;;) { while(MT.schedule()); // do everything we can do if(MT.noProcesses()) // exit if no processes are left break; if(!fgets(line,sizeof(line),stdin)) break; MT.sendEvent(*line-'0'); } }
void printer(void *p) { char c=(char)p; for(;;) { cout<<c<<endl; MT.yield(); } } int main() { MT.makeThread(printer,(void*)'a'); MT.makeThread(printer,(void*)'b'); for(;;) { while(MT.schedule()); // do everything we can do if(MT.noProcesses()) // exit if no processes are left break; } }