6

In java, there is nice package java.util.concurrent which holds implementation for BlockingQueue interface.

I need something similar in Haskell, so it will be able to

  • maintain fixed size of queue in memory
  • block read operations when queue is empty (get)
  • provide time-boxed blocks, which will return Nothing if queue is empty and timeout exceeded
  • similar for put operations - block until queue has capacity with time-boxed version

probably this could be implemented with STM or blocking transactions - but I was not able to find something like that on hackage.

jdevelop
  • 12,176
  • 10
  • 56
  • 112

3 Answers3

7

A concurrent queue is often called a Chan (channel) in Haskell, and as you might expect, there is indeed a BoundedChan package on Hackage which looks like it should fit your needs, except for timeouts. However, you should be able to get that by using System.Timeout.

hammar
  • 138,522
  • 17
  • 304
  • 385
  • Yes, that seems good, combine that with timeout from System.Timeout for the time-boxed block and jdevelop has exactly what he asked for :) – Jedai Feb 12 '12 at 11:50
  • Does Chan work with multiple producers/consumers? May I start N producers, supply them with the blocking queue and then start M consumers which will take data from that queue? AFAIR channel is dedicated to single producer->single consumer model, which is not my case. – jdevelop Feb 12 '12 at 11:54
  • 2
    Chan works perfectly well with multiple producers/consumers (though when you read an element from the queue it's gone, but I guess that goes without saying) what makes you think channel is for single producer->single consumer ? (You can utilize dupChan to get broadcast instead of the normal behavior) – Jedai Feb 12 '12 at 11:57
3

I need to give a small warning. The source of BoundedChan shows that it is not exception safe. If you know you are exception free, for example you avoid killThread, then this will be okay. If you want a bulletproof library then you will have to improve on BoundedChan. An exception safe library will be using withMVar or bracket instead of takeMVar and putMVar.

Using STM would avoid most of the exception safety issue, and this can be composed with System.Timeout. Also, timeout has been wrapped a few ways on Hackage.

Chris Kuklewicz
  • 8,123
  • 22
  • 33
3

The stm-chans package contains a wide variety of channels for STM. It seems to be more actively maintained than the BoundedChan package hammar mentioned (which was last updated in 2009), and thanks to its use of STM, it'll be exception-safe.

I believe its TBChan variant, in conjunction with System.Timeout, meets all your requirements.

ehird
  • 40,602
  • 3
  • 180
  • 182