On Wed, 1 Sep 2004 15:26:52 -0700 (PDT) David Morris <[EMAIL PROTECTED]> wrote:

DM> There is no way for a C implementation to insure this is atomic unless the
DM> hardware has an instruction to perform the operation atomically.

 This is true, but Win32 and pthreads both allow to do it so for most of
the modern platforms supported by cclient it is possible to do it.

DM> With modern desk top and larger computers, fetching or storing a 32 bit
DM> value should be atomic. A trick I use to guard one-time code is:
DM> 
DM>    if (!initialized) {
DM>       getmutex()
DM>       if (!initialized) { // real test guarded by mutex
DM>         do heavy lifting
DM>         initialized=TRUE
DM>       }
DM>       freemutex()
DM>    }
DM> 
DM> This approach is a light weight test for the common case that
DM> initialization is complete but is 100% accurate since the test is repeated
DM> under protection of the mutex.

 Although this mostly does work in practice please see an article in a
recent (August I believe) Dr Dobbs journal issue which explains why this
doesn't have to always work, i.e. is not portable. Basically, an optimizing
compiler is perfectly free to reorder the "do heavy lifting" and
"initialization=TRUE" lines which could result in using uninitialized
object. To ensure that it does work as expected, a memory barrier needs to
be inserted between these 2 lines -- and, of course, there is no portable
way to do this in C neither.

 Regards,
VZ

-- 
------------------------------------------------------------------
 For information about this mailing list, and its archives, see: 
 http://www.washington.edu/imap/c-client-list.html
------------------------------------------------------------------

Reply via email to