Re: Multitasking in Mac OS Gets 100% CPU
- Posted by ghaberek (admin) Nov 06, 2012
- 1446 views
I get this behavior on Linux. I would expect Windows to show the same thing. Most of the time is spent in the while loop:
while t1_running or t2_running do if get_key() = 'q' then exit end if task_yield() end while
The other tasks don't run very often, so control returns here. When you yield here, control typically comes right back, because the other tasks aren't ready to run yet.
I tried this in WinXP, and I think it's actually using all of the CPU there, but some of it is reported for csrss.exe. The multitasking on Windows is implemented with Fibers, and I think that Fiber related activity shows up under csrss.exe. The CPU is definitely pegged while the program is running.
On Linux, throwing sleep(1) into the main loop seems to keep the CPU usage under control (practically 0%). Using sleep(0) or any fraction < 1 (e.g. sleep(0.01)) has no effect and the CPU still spikes to 100%.
while t1_running or t2_running do if get_key() = 'q' then exit end if task_yield() sleep(1) -- toggle between 0 or 1 and observe the outcome end while
Interestingly, checking gnome-system-monitor with sleep(1) the "Waiting Channel" column displays hrtimer_nanosleep, but with sleep(0) it simply shows "0". Is the sleep() function not calling "nanosleep" when we pass 0 as a parameter?
-Greg