Need help with communication between multiple threads

Chad J gamerChad at
Tue Feb 20 17:02:10 PST 2007

kris wrote:
> Basicially, you need to protect the value from contention between two 
> threads. There are a number of ways to do this:
> 1) using native D facilities via the synchronized keyword: expose a 
> getter and setter method, and have them both synch on the same 
> object/lock. This is a fairly heavyweight resolution, but it would work.

So would something like this do the trick?

class Mutex
     uint pointlessVariable;
Mutex mutex;

uint m_value = 42; // The thing to be protected.
uint value() // getter
         return m_value;
uint value(uint newbie) // setter
         m_value = newbie;

     return newbie;

Or am I supposed to do something else like put m_value inside the mutex 

> 2) get under the covers and utilize a mutex, semaphore, or some other 
> classical synchronization construct exposed by the OS itself. Tango will 
> provide a cross-platform way of doing this in the next release. This is 
> potentially lighter weight than #1

I suppose I'll wait for that release and see what happens.

> 3) use CPU-specific instructions to ensure value access is atomic. This 
> is what Sean has exposed in the Atomic module within Tango. It is a 
> lightweight and low-overhead solution, and works by locking the bus for 
> the duration of the read/write access.

This sounds cool, but I don't quite understand how to use the Atomic 
module - what is msync and which value of it do I pick to make things 
work?  I made a post about this in the Tango forum incase it's more 
appropriate to discuss there.

> 4) use a small discrete unit for the value. If value is just a byte, the 
> underlying hardware will usually treat it as an indivisible unit, giving 
> you the desired result (similar to #3). However, there are memory 
> barriers involved also, which D respects via the "volatile" keyword. 
> Beyond that, there may be issues with cache-reconciliation on a 
> multi-core device, so this approach is generally not recommended.

Right, I'll just stay away from that.

> - Kris

When I was porting Phobos to work on ARM-WinCE, it was very helpful to 
be able to discard a module without breaking other parts of the lib, 
namely in the case of that module requiring a broken language feature or 
inline assembly (inline asm is not currently available with 
arm-wince-pe-gdc, and I don't feel like learning ARM asm yet).  That 
said, Atomic looks like it will be very broken on ARM in its current 
state.  I also benchmarked synchronized reads vs atomic reads and yeah, 
synchronized was much slower (I picked "whatever makes it compile" 
values for msync).  So I'll probably implement a version using only 
synchronization and a version that uses Atomic instead whenever possible.

More information about the Digitalmars-d-learn mailing list