2009/11/10 Giovanni Gigante <giov@...>:
> Which of the following operations are thread-safe, i.e. in which of the
> following (if any) a thread can access a global variable without the
> need for a locking mechanism?
> a) aref
> b) aref 
> c) setf aref
> d) setf aref 
Depends on your definition of thread safety.
Eg. (setf (aref x 0) (1+ (aref x 0))) is by no means guaranteed to
increment the element by one -- other threads may write in between.
Also: if the array is non-simple, the result may be lost if the
underlying array that is updated is replaced by another thread.
If you assume that the array is simple, then all of these operations
are thread safe -- there will never by "intermediate garbage" values
anywhere, but threads may stomp on each other unless you take care to
lock around shared data as per the example above.
> e) gethash
> f) gethash 
> g) setf gethash
> h) setf gethash 
Please see the documentation for MAKE-HASH-TABLE, paying attention to
the :SYNCHRONIZED keyword (below):
If NIL (the default), the hash-table may have multiple
but results are undefined if a thread writes to the hash-table
concurrently with another reader or writer. If T, all
are safe, but note that CLHS 3.6 (Traversal Rules and Side Effects)
remains in force. See also: SB-EXT:WITH-LOCKED-HASH-TABLE. This keyword
argument is experimental, and may change incompatibly or be
removed in the
CL-USER> (describe 'sb-ext:with-locked-hash-table)
WITH-LOCKED-HASH-TABLE names a macro:
Lambda-list: ((HASH-TABLE) &BODY BODY)
Limits concurrent accesses to HASH-TABLE for the duration of BODY.
If HASH-TABLE is synchronized, BODY will execute with exclusive
ownership of the table. If HASH-TABLE is not synchronized, BODY will
execute with other WITH-LOCKED-HASH-TABLE bodies excluded -- exclusion
of hash-table accesses not surrounded by WITH-LOCKED-HASH-TABLE is
(incf (getash key table)))
is guaranteed to be atomic if the hash-table is synchronized. If the
table is synchronized, but you leave out the WITH-LOCKED-HASH-TABLE,
the table will not be corrupted, but threads may stomp on each other
and the incrementation will not work properly.