Atomic operations are special operations where you don't have to worry about some other process messing with things while the operation is taking place.
For a simple example of why atomic operations are important:
The naive, non-atomic implementation:
- reads the value in the memory location;
- adds one to the value;
- writes the new value back into the memory location.
Now, imagine two processes are running incrementing a single, shared memory location:
- the first process reads the value in memory location;
- the first process adds one to the value;
but before it can write the new value back to the memory location it is suspended, and the second process is allowed to run:
- the second process reads the value in memory location, the same value that the first process read;
- the second process adds one to the value;
- the second process writes the new value into the memory location.
The second process is suspended and the first process allowed to run again:
-
the first process writes a now-wrong value into the memory location, unaware that the other process has already updated the value in the memory location.
Atomic operations fix this problem by preventing (STM is a little fancier and doesn't actually _prevent_, but you can pretend that it does) any other process from writing to the memory in question until the computation is finished and the result is written back.
For many simple cases something like atomicModifyIORef is all you really need. However, if you have cases where you need to make sure _multiple_ IORefs/MVars/TVars/etc.. are not written to until you're finished then you really need something like STMs 'atomically' function. Which runs a block of STM operations "atomically".
- Job
On Wed, Jul 28, 2010 at 8:23 PM, Eitan Goldshtrom
<thesourceofx@gmail.com> wrote:
Hi everyone. I was wondering
if someone could just guide me toward some good information, but if
anyone wants to help with a personal explanation I welcome it. I'm
trying to write a threaded program and I'm not sure how to manage my
memory. I read up on MVars and they make a lot of sense. My real
question is what is "atomic" and how does it apply to TVars? I don't
understand what atomic transactions are and I can't seem to find a
concise explanation. I also saw some stuff about TMVars? But I can't
find much on them either. Any help would be appreciated.
-Eitan
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe