I need to store a buffer of some values in STM. Writer threads need to monitor the buffer’s size. I started to implement this thing using TChan but than I found out that the API does not provide a way to measure the length of the channel. Being a one stubborn fella I then implemented the thing myself:
readTChanLength ch = do
empty <- isEmptyTChan ch
if empty
then return 0
else do
value <- readTChan ch
length <- readTChanLength ch
unGetTChan ch value
return $ 1 + length
Now everything works fine, but I am wondering what the reasons for such a trivial thing not to be implemented in the standard library are and what the preferred approach to that sorta problem is. I realize that this algorithm has at least an O(n) complexity, but it can’t be the reason, right?
The preferred approach is to keep a counter with the channel, and atomically increment the counter while writing the channel, and decrementing the counter when reading the channel.
Your solution traverses through all element of the channel, which will probably not work well for actual high-concurrent workloads.