Bug 44412 - Thread.Sleep(1) consumes 100% of CPU time on OSX
Summary: Thread.Sleep(1) consumes 100% of CPU time on OSX
Status: REOPENED
Alias: None
Product: Runtime
Classification: Mono
Component: General (show other bugs)
Version: unspecified
Hardware: Macintosh Mac OS
: --- normal
Target Milestone: ---
Assignee: Alexis Christoforides
URL:
Depends on:
Blocks:
 
Reported: 2016-09-16 10:46 UTC by Alexei Garbuzenko
Modified: 2016-10-03 21:22 UTC (History)
3 users (show)

See Also:
Tags:
Is this bug a regression?: ---
Last known good build:


Attachments
Threading.Sleep sample (187 bytes, text/plain)
2016-09-19 15:39 UTC, Alexis Christoforides
Details
Thread.Sleep loop sample (229 bytes, text/plain)
2016-09-19 15:45 UTC, Alexei Garbuzenko
Details

Description Alexei Garbuzenko 2016-09-16 10:46:14 UTC
Guys, I found out that one of my Mono projects on Mac is having 100% CPU usage without any real load. Funniest thing that under Wine on the same machine it didn't have that problem.
I dig a lot and found that Mono's System.Threading.Thread.Sleep() resides on clock_nanosleep on non-windows platforms. That is generally good on Linux, but not on FreeBSD, Solaris and Mac OS X that don't have native clock_nanosleep at all and some substitution is performed instead. Thread.Sleep() is not a high precision timer, it does not need nanosecond resolution and can be easily fixed by using usleep, clock_sleep or even with mach_wait_until. Any of those lowers CPU usage in my case to 0-3% without any precision loss. 
Even more, lot's of games are using Mono, MonoGame or Unity these days and games usually have loops with Thread.Sleep(1) inside. Those games on Mac OS X are heating the CPUs without any purpose meaning that millions of computers around the world right now uses excess power just because of clock_nanosleep!
So let's lower worldwide CO emission and excessive power usage by just fixing that one function!
Thanks
Comment 1 Alexis Christoforides 2016-09-19 15:38:11 UTC
Hello,

I've not been able to reproduce this using the trivial test attached below. Could you provide a example that shows the 100% CPU behavior you have seen?
Comment 2 Alexis Christoforides 2016-09-19 15:39:05 UTC
Created attachment 17595 [details]
Threading.Sleep sample
Comment 3 Alexei Garbuzenko 2016-09-19 15:45:46 UTC
Created attachment 17596 [details]
Thread.Sleep loop sample
Comment 4 Alexei Garbuzenko 2016-09-19 15:48:59 UTC
Single Thread.Sleep call won't give you any significant CPU usage, you have to call it in a loop. It's common practice in games, multithreaded apps, network servers, etc.
Comment 5 Alexei Garbuzenko 2016-09-24 17:40:18 UTC
Any update?
Comment 6 Alexei Garbuzenko 2016-10-03 21:22:54 UTC
Reopening this one. It's critical for infinite loops with Tread.Sleep(1)

Note You need to log in before you can comment on or make changes to this bug.