On 01/03/2011 16:59, d coder wrote:

 > I'm afraid that I have no idea what would be "stale" about a shared
variable.
 > sychronized uses a mutex, and if you want to avoid race conditions,
you need to
 > use mutexes or something similar when dealing with shared variables.
But I don't
 > know what would be "stale" about a variable.
 >

One thread modifies a shared variable and the other thread still gets an
old value. I do not know if this is applicable to D at all. Just wanted
to get a clarification after I read an article in "Java Concurrency in
Practice" book. I quote a relevant paragraph:

    Locking is not just about mutual exclusion; it is also about memory
    visibility. To ensure that all threads see the most up-to-date
    values of shared mutable variables, the reading and writing must
    synchronize on a common lock.


Regards
Perhaps what you mean is synchronising a function vs shared data object.

If you have one Function A and some data D, then so long as ONLY function A (and it's callees) change or read D, then everything should work fine. Hence you're synchronising function A (or putting it in a critical section)


However, if you have two functions A and B, and data D. If function A and B can read and or write to the data D, then thread 1 can execute in A (but no other if it's synchronised) But, it may be pre-empted and another thread can then start executing in function B that is also synchronised. The problem here is that function A is half way though execution when B starts, hence you could likely have data in D that has been partially changed, "old" other otherwise inconsistent, which can cause problems, or even proper disasters.

The answer in this case is to have a mutex to protect D, so function A or B must obtain this and hold it while is modifies data D. Any other function will then have to wait for the mutex to be unlocked before reading or writing.


Reply via email to