Need help with communication between multiple threads
kris
foo at bar.com
Tue Feb 20 10:30:54 PST 2007
Chad J wrote:
> I'm a bit of a newbie to this whole multithreading thing, so I'm hoping
> someone can help me with this.
>
> First, what I know (or what I think I know): So I've been reading about
> this, and apparently there's this problem where two threads that are
> reading a value from the same address in memory at the same time may end
> up with two completely different values. Apparently this is because
> when you write something, it may just end up in the cache and not be
> updated in global memory. Also, when reading, you may end up with
> something that is just an outdated copy in the cache, and not the actual
> thing from global memory. But it doesn't stop there, apparently x86
> computers are very forgiving on this stuff so if you make a mistake you
> won't know it until your program is run on some more obscure hardware.
>
> Now then, my question: In D, how do I ensure that when I write
> something, the write is to global memory, and when I read something, the
> read is from global memory?
>
> Some more info: This comes up because I am trying to write a Timer
> class for Tango, and it will include timers that trigger events at a
> later date, which requires multithreading. So it'd be most helpful if I
> could accomplish this using only D features and/or Tango.
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.
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
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.
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.
- Kris
More information about the Digitalmars-d-learn
mailing list