Ticket #5911: 0003-Add-newBroadcastTChan-and-newBroadcastTChanIO.patch

File 0003-Add-newBroadcastTChan-and-newBroadcastTChanIO.patch, 2.2 KB (added by joeyadams, 3 years ago)

Add newBroadcastTChan and newBroadcastTChanIO

  • Control/Concurrent/STM/TChan.hs

    From 65f52c3b0eb106f6a0921a640e38fbf01811ea23 Mon Sep 17 00:00:00 2001
    From: Joey Adams <[email protected]>
    Date: Fri, 2 Mar 2012 21:10:51 -0500
    Subject: [PATCH 3/4] Add newBroadcastTChan and newBroadcastTChanIO
    
    ---
     Control/Concurrent/STM/TChan.hs |   36 ++++++++++++++++++++++++++++++++++++
     1 files changed, 36 insertions(+), 0 deletions(-)
    
    diff --git a/Control/Concurrent/STM/TChan.hs b/Control/Concurrent/STM/TChan.hs
    index 3477d88..9a127bf 100644
    a b module Control.Concurrent.STM.TChan ( 
    2626        TChan, 
    2727        newTChan, 
    2828        newTChanIO, 
     29        newBroadcastTChan, 
     30        newBroadcastTChanIO, 
    2931        readTChan, 
    3032        tryReadTChan, 
    3133        peekTChan, 
    newTChanIO = do 
    6870  write <- newTVarIO hole 
    6971  return (TChan read write) 
    7072 
     73-- | Create a write-only 'TChan'.  More precisely, 'readTChan' will 'retry' 
     74-- even after items have been written to the channel.  The only way to read 
     75-- a broadcast channel is to duplicate it with 'dupTChan'. 
     76-- 
     77-- Consider a server that broadcasts messages to clients: 
     78-- 
     79-- >serve :: TChan Message -> Client -> IO loop 
     80-- >serve broadcastChan client = do 
     81-- >    myChan <- dupTChan broadcastChan 
     82-- >    forever $ do 
     83-- >        message <- readTChan myChan 
     84-- >        send client message 
     85-- 
     86-- The problem with using 'newTChan' to create the broadcast channel is that if 
     87-- it is only written to and never read, items will pile up in memory.  By 
     88-- using 'newBroadcastTChan' to create the broadcast channel, items can be 
     89-- garbage collected after clients have seen them. 
     90newBroadcastTChan :: STM (TChan a) 
     91newBroadcastTChan = do 
     92    dummy_hole <- newTVar TNil 
     93    write_hole <- newTVar TNil 
     94    read <- newTVar dummy_hole 
     95    write <- newTVar write_hole 
     96    return (TChan read write) 
     97 
     98-- | @IO@ version of 'newBroadcastTChan'. 
     99newBroadcastTChanIO :: IO (TChan a) 
     100newBroadcastTChanIO = do 
     101    dummy_hole <- newTVarIO TNil 
     102    write_hole <- newTVarIO TNil 
     103    read <- newTVarIO dummy_hole 
     104    write <- newTVarIO write_hole 
     105    return (TChan read write) 
     106 
    71107-- |Write a value to a 'TChan'. 
    72108writeTChan :: TChan a -> a -> STM () 
    73109writeTChan (TChan _read write) a = do