Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blocking queue implementation in Haskell

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.

like image 300
jdevelop Avatar asked Feb 12 '12 11:02

jdevelop


3 Answers

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.

like image 117
hammar Avatar answered Sep 20 '22 02:09

hammar


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.

like image 44
ehird Avatar answered Sep 22 '22 02:09

ehird


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.

like image 35
Chris Kuklewicz Avatar answered Sep 22 '22 02:09

Chris Kuklewicz