[Haskell-cafe] Race condition possible?
paul at cogito.org.uk
Sat Feb 14 14:01:39 EST 2009
Peter Verswyvelen wrote:
> Consider the following code
> stamp v x = do
> t <- getCurrentTime
> putMVar v (x,t)
> Is it possible - with GHC - that a thread switch happens after the t
> <- getCurrentTime and the putMVar v (x,t)?
> If so, how would it be possible to make sure that the operation of
> reading the current time and writing the pair to the MVar is an
> "atomic" operation, in the sense that no thread switch can happen
> between the two? Would this require STM?
> Thanks again for sharing your wisdom with me :)
I'm not entirely sure what you are trying to achieve here. Presumably
you want v to contain the (value, time) pair as soon as possible after
time "t". Of course it won't be instantaneous. So another thread could
observe that at time (t+delta) the variable "v" does not yet contain
(x,t). Is this a problem?
Atomic transactions won't work because "getCurrentTime" is of type "IO
Time", whereas anything inside "atomic" has to be of type "STM a".
In theory you could lock out context switches by messing around with the
GHC runtime, but if you are running on a multicore machine then that
won't work either.
More information about the Haskell-Cafe