[Openmcl-devel] [openmcl-devel] atomic-incf

Gary Byers gb at clozure.com
Thu Oct 15 22:38:30 UTC 2009


I'm not sure that I understand the question fully.  To the extent
that I do: yes, ATOMIC-INCF is thread-safe in that:

  - it behaves the same way, regardless of how many threads are
    trying to modify the same memory location.
  - it can be used to achieve the same effects that might otherwise
    require more heavyweight mechanisms to ensure thread-safety.

For instance: suppose that a number of threads were processing "requests"
(it doesn't matter what "requests" are) and we want to know how many
requests have been completed and maintain a global *REQUESTS-COMPLETED*
variable to track that information.  If each thread does something like:


  ...
  (process-request)
  (incf *REQUESTS-COMPLETED*)

then *REQUESTS-COMPLETED* may be at least slightly inaccurate: multiple
threads can't safely update a shared memory location concurrently in this
way because the read/modify/write sequences that they'd use aren't atomic.

We -could- use a lock to ensure that that doesn't happen:

  ...
  (process-request)
  (with-lock-grabbed (*REQUESTS-COMPLETED-LOCK*)
    (incf *REQUESTS-COMPLETED*))

and that'd be thread-safe, but grabbing a lock (and releasing it, and
using UNWIND-PROTECT to guarantee that that the lock is released) is
a fairly heavy price to pay to increment a variable safely.

We could also do:

  ...
  (process-request)
  (atomic-incf *REQUESTS-COMPLETED*)

and that'd also be thread-safe (we can say that each thread has
exclusive access to the global variable for the few instructions
it takes to increment its value) and less expensive than using
a lock would be.

So yes, what ATOMIC-INCF does is thread-safe and it can also
be used to do things in a thread-safe way (with less overhead
than other mechanisms incur.)




On Thu, 15 Oct 2009, David L. Rager wrote:

> Hi Gary,
>
> I'm pretty sure I understand the multi-threading issue.  Even if it
> were a single CISC instruction, there would be no "atomicity"
> guarantee without the lock on the memory address (where the lock
> prohibits reading/writing of that address).
>
>> ATOMIC-INCF basically tries to guarantee that the
>> read-modify-write sequence happens atomically.
>> I think that we could actually implement it as
>>
>>  (lock)
>>  (addq ($ fixnumone) (@ loc))
>>
>> or
>>
>>  (movq increment-by (% reg))
>>  (lock)
>>  (addq (% reg) (@ loc))
>>
>> on x86; we actually do a similar compare-and-swap loop on both
>> architectures.
>
> So do we know whether the atomic-incf in CCL version 1.3 of
> x86-misc.lisp is thread-safe?  I'm happy to go read more about the X86
> assembly "specification" in order to better understand the code myself
> if that's what's required.
>
> Thanks,
> David
>
>


More information about the Openmcl-devel mailing list