guile-user
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Some introductory docs about C level threading


From: Ken Raeburn
Subject: Re: Some introductory docs about C level threading
Date: Tue, 1 Feb 2005 12:37:36 -0500

On Jan 21, 2005, at 13:29, Marius Vollmer wrote:
4.3.5 Multi-Threading
---------------------
     SCM
     my_list_to_vector (SCM list)
     {
       SCM vector = scm_make_vector (scm_length (list), SCM_UNDEFINED);
       size_t len, i;

       len = SCM_SIMPLE_VECTOR_LENGTH (vector);
       i = 0;
       while (i < len && scm_is_pair (list))
         {
           SCM_SIMPLE_VECTOR_SET (vector, i, SCM_CAR (list));
           list = SCM_CDR (list);
           i++;
         }

       return vector;
     }

   It is safe to use `SCM_CAR' and `SCM_CDR' on the local variable LIST
once it is known that the variable contains a pair.  The contents of
the pair might change spontaneously, but it will always stay a valid
pair (and a local variable will of course not spontaneously point to a
different Scheme object).

But is it guaranteed that, without locking, SCM_CAR and SCM_CDR will always return the "before" or "after" values while another thread is modifying them, and not some corrupted intermediate form? Given typical data alignment and access, and hardware memory management techniques, and the small size of a SCM value, I'm not aware of a situation where it would be at all likely to happen, but I'm also not aware of any guarantee that it won't.

Though, even without weird memory management issues, consider:
  SCM_SETCAR(x, SCM_I_MAKINUM(i >> 2))    i some external int var
 -> (....x)[0] = ((... i >> 2) << 2 + scm_tc2_int)
-> copy i, masking off bottom two bits, into target location; then add in scm_tc2_int

If SCM_CAR(x) is read at just the wrong time, the tag bits might not be correct.

It may also be the case that if both the car and cdr of the pair (or indeed, any two separate locations) are modified in one thread and read in another, the memory accesses could be reordered (by the compiler, or even by the CPU these days) such that the read-back contents of the pair don't seem to match the "before" or "after" values or even the expected intermediate state where the first-listed modification has been done but the second has not.

If someone's got lots more experience with multithreaded systems and wants to say I'm wrong, great. I've been thinking about this a bit lately, trying to make a pile of code thread-safe at work, but I'm mostly coming at it from a theoretical perspective.

Ken





reply via email to

[Prev in Thread] Current Thread [Next in Thread]