
áÎÄÒÅÊ óÅÍÁÛÅ× <andysem@mail.ru> writes:
-----Original Message----- From: Anthony Williams <anthony_w.geo@yahoo.com> To: boost@lists.boost.org Date: Thu, 20 Sep 2007 16:46:11 +0100 Subject: Re: [boost] lightweight_once
Andrey Semashev <andysem@mail.ru> writes:
Hello Anthony,
Tuesday, August 28, 2007, 12:17:45 PM, you wrote:
Would you be interested to take a look at my implementation? Maybe after some cleaning up it could be moved to your official library?
Sorry for the delay in replying.
I've looked at the implementation in FSM.zip from the vault --- is that the one you meant? --- and with a quick glance it looks like you've opted for a check/sleep/check/sleep loop for threads that are waiting for another thread to finish running the routine. This is a bad idea. Blocking of this nature should be done by waiting on an OS primitive rather than with a wait loop.
Why is it that bad? This is safier since there is no opportunity to get an error on the threading primitive construction, it doesn't use system resources like kernel objects and it solves the fundamental problems of creating and destroying those threading primitives in run time. And it will be run only once after all, so performance is not an issue.
I think that performance *is* an issue, even though this will only be run once per thread. A check/sleep polling loop is a bad idea, as it consumes CPU time that could be spent actually running the once routine (or another thread that doesn't need to wait). By waiting on an OS primitive, the OS can take the thread out of the schedule until the primitive is ready to be acquired. Not only that, but a check/sleep loop forces a latency of at least the specified sleep time on the waiting thread. If the initialization being waited for only takes a few microseconds (or less --- if it's just a simple initialization it might take only a few nanoseconds), then waiting a whole millisecond is an unnecessary delay. POSIX provides pthread_once. We should use it. The Windows Vista functions look to supply a similar facility, and do at least allow the passing of a parameter to the routine without using TSS. Anthony -- Anthony Williams Just Software Solutions Ltd - http://www.justsoftwaresolutions.co.uk Registered in England, Company Number 5478976. Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL