
Originally Posted by
vratojr
Thanks, but if I am not too annoying, could you explain me why I can't use the while?Is this because I continuosly pool on a member of another thread and this generates a conflict with the owner thread?
It's because you are waiting in a so called "busy loop".
Try to compile such program:
int main(){ while(1); return 0; }
int main(){ while(1); return 0; }
To copy to clipboard, switch view to plain text mode
Run it and see the CPU usage. You'll notice that it'll go up to 100%.
Now compile and run this one:
int main(){ while(1) sleep(0); return 0; }
int main(){ while(1) sleep(0); return 0; }
To copy to clipboard, switch view to plain text mode
This one won't eat up all your CPU power (and it'll be easier to kill such a task) -- this is called "semi-busy loop". The only difference between those two applications is that the second one forces a context switch of the processor (changes the "active" process) allowing other applications to run. As a result all your applications will run more efficiently.
The "next step" is to use some kind of lock which will suspend your process (thread) and wake it up only where a certain condition is met. A pseudocode follows:
//...
// instead of while(!someEventHappened); -- busy loop
// or instead of while(!someEventHappend) sleep(0); -- semi busy loop
goToSleepUntil(someEventHappend);
doSomething();
//...
//...
// instead of while(!someEventHappened); -- busy loop
// or instead of while(!someEventHappend) sleep(0); -- semi busy loop
goToSleepUntil(someEventHappend);
doSomething();
//...
To copy to clipboard, switch view to plain text mode
I mean, theoretically I could resolve this also by placing a mutexlocker in run() and in inzializzato()?
I think so (depends where exactly you want to put it), but using a wait condition is more "elegant".
Excuse me but I want also to learn!
Good for you
Bookmarks