|
From: | Dirk Herrmann |
Subject: | Re: scm_i_fraction_reduce thread safety |
Date: | Tue, 27 Jan 2004 23:15:39 +0100 |
User-agent: | Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4) Gecko/20030821 |
Carl Witty wrote:
On Tue, 2004-01-20 at 16:00, Marius Vollmer wrote:if fraction is not reduced: lock if fraction is not reduced: reduce it unlock read itI'm afraid this doesn't work. The idiom is known as "double-checked locking"; see http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html for an explanation of why it doesn't work. (Briefly: the "reduce it" code will do something like the following: write numerator, write denominator, write "fraction is reduced" marker. The compiler is allowed to re-order these writes, so the "fraction is reduced" marker is written before the numerator and denominator. Even if it does not, on a multi-processor machine, the memory system may reorder these writes between processors, unless you put (expensive and non-portable) "memory barrier" instructions in the appropriate places.)
Interesting - and makes me nervous. If one thread uses the code (set-cdr! pair (cons #t #t))then this will translate into the writing of three memory locations, namely the car and cdr of the new cell plus the cdr of the old cell. If these write can get arbitrarily re-ordered, then a second thread may access
(cdr pair)and find the reference to the new cell, which is not yet initialized. Accessing the uninitalized new cell might lead to a crash of the second thread (I have not thoroughly checked this) . Certainly, this way of accessing memory is wrong, since the user should have done some locking between the two threads. But, (if my assumption is right) the bad thing is, that we are dealing with pure scheme code here, and only the fact that we run the code in a multithreaded environment instead of within a single thread can cause pure scheme code to crash. One might say this is also true for all other kinds of programs when thrown into a multi-threaded environment. But, for guile we had up to now the goal of keeping pure scheme code crash free.
The underlying problem here is, that guile's space of cells is actually shared memory between all threads. To make things transparently safe for scheme code would either forbid thread switches to happen at certain points in time (which makes concurrent threads impossible), or to add a lot more locking when accessing the cell space.
Am I missing something here? Best regards, Dirk Herrmann
[Prev in Thread] | Current Thread | [Next in Thread] |