[En-Nut-Discussion] MultiThreading
Ole Reinhardt
ole.reinhardt at kernelconcepts.de
Tue Mar 27 17:59:37 CEST 2007
Hi,
> I have the same question again.
> I habe two threads (one for networking nad second for computing and 2 other threads main and idle).
> I don't know which functions should i use, i am confused in them.
> Nutthreadyield()
Thin function gives up CPU to another runable thread.
> nutthreadswitch()
AFAIK you may not use thins function directly.
> nutsleep()
This function will sleep for a minimum of the given time or will do
(nearly) the same as NutThreadYield()
> OR
> nuteventwait() & nuteventpost()
Normaly you'll want to use these two functions. On a coopearative
Multithreading as NutOS implements it a thread will always run as long
as it does not reach a thread switching point. These are for example the
functions mentioned above.
NutOS hardware IO functions use NutEventWait() / -Post() in most cases
to wait on external events (like incomming data, timer, interrupts,
etc...) so if you run into these functions and no data is available your
thread will be stopped implecitly and cpu is given up to another
function.
So for example: A thread reading from an uart in this way:
while (1) {
fgetc(uart);
}
won't never block the cpu, as fgetc() will give up cpu to another thread
if there is no data available on the uart filedescriptor.
No, if you implement own threads that needs to synchronise you use
NutEventWait() / -Post(). NutEventWait() will block the currently
running thread and give up cpu until an other thread calls
NutEventPost() on the same handle.
For example these three threads implement a pedestrian light (ok, a
little bit over engeneered)
THREAD(BUTTON) {
while (1) {
WaitUntilButtonPressed();
NutEventPost(BUTTON_EVENT);
}
}
THREAD(PEDESTRIAN_LIGHT) {
while(1) {
NutEventWait(TRAFFIC_RED);
GreenLight();
NutSleep(5 sec);
RedLight();
NutEventPost(PEDESTRIAN_RED);
}
}
THREAD(TRAFFIC_LIGHT) {
while(1) {
NutEventWait(BUTTON_EVENT);
RedLight();
NutEventPost(TRAFFIC_RED);
NutEventWait(PEDESTRIAN_RED);
GreenLight();
}
}
Hope this helps a little bit. You should perhaps read the NutOS software
manual and the NutOS Thread API again and perhaps some books about
operation system design and implementation to get a better overview
about thread synchronisation and multi threading technics.
Best regards,
Ole Reinhardt.
--
kernel concepts GbR Tel: +49-271-771091-14
Inh. Faerber & Kirchner Fax: +49-271-771091-19
Sieghütter Hauptweg 48 Mobil: +49-177-7420433
D-57072 Siegen UstID: DE 205 648 898
More information about the En-Nut-Discussion
mailing list