skip-var-0.1.1.0: Skip variables

Copyright(c) Daniel Taskoff 2018
Georgi Lyubenov 2018
LicenseMIT
Maintainerdaniel.taskoff@gmail.com, godzbanebane@gmail.com
Stabilityexperimental
Safe HaskellSafe
LanguageHaskell2010

Control.Concurrent.SVar

Contents

Description

Implementation of skip variables - a special case of skip channels, the difference being that a value stored in a skip variable can be read at most once, while a skip channel can have multiple readers (i.e. multiple readers can read the same value).

Writing into a skip variable doesn't block - if there's a value stored, it's overwritten. Reading, on the other hand, blocks, if there isn't a new value since the last read, or if the skip variable is empty.

Some examples:

s <- newEmptySVar :: IO (SVar Int)
print =<< readSVar s -- blocks
s <- newSVar 42 :: IO (SVar Int)
print =<< readSVar s -- prints 42
print =<< readSVar s -- blocks

The next few lines will print some of the numbers between 0 and 10000. Note that at least one number will be printed, but many will be skipped, because printing is slow.

import Control.Concurrent (forkIO, killThread)
import Control.Monad (forever)

s <- newEmptySVar :: IO (SVar Int)
tid <- forkIO $ forever $ print =<< readSVar s
mapM_ (putSVar s) [0..10000]
killThread tid
Synopsis

SVar

data SVar a Source #

An SVar (skip variable) is a variable which allows for non-blocking updates, and blocking reads if the stored data has been read already, or if there is no data.

Creation of SVars

newEmptySVar :: IO (SVar a) Source #

Create an empty SVar.

newSVar :: a -> IO (SVar a) Source #

Create an SVar which contains the supplied value.

Modification of SVars

putSVar :: SVar a -> a -> IO () Source #

Put a value into an SVar. Never blocks, always overwrites the current value, if there is one.

readSVar :: SVar a -> IO a Source #

Read a value from an SVar. Blocks if there isn't a new value since the last read, or if the SVar is empty.