title: Avoiding multithreading issues with the WebSocket library
body: <p>The <a href="https://hackage.haskell.org/package/websockets" rel="nofollow noreferrer">WebSockets</a> library contains an open <a href="https://github.com/jaspervdj/websockets/issues/208" rel="nofollow noreferrer">issue</a> about sending messages from multiple threads.<br />
  As an example I took a look at <a href="https://github.com/hashrocket/websocket-shootout/blob/master/haskell/warp/Main.hs" rel="nofollow noreferrer">websocket-shootout</a>, and noticed a forked thread for <a href="https://hackage.haskell.org/package/websockets-0.12.7.3/docs/Network-WebSockets.html#v:receiveData" rel="nofollow noreferrer">receiveData</a>.</p>
  <pre class="lang-hs prettyprint-override"><code>void $ fork $ silentLoop (Unagi.readChan readEnd &gt;&gt;= Ws.sendTextData conn)
  
  silentLoop $ do
    msg &lt;- Ws.receiveData conn
  
    case parseMsg msg of
      Nothing -&gt; Ws.sendClose conn (&quot;Invalid message&quot; :: LByteString)
  
      Just Echo -&gt; Ws.sendTextData conn msg
  
      Just (Broadcast res) -&gt; do
        Unagi.writeChan writeEnd msg
        Ws.sendTextData conn res
  </code></pre>
  <p>I was under the impression from the open issue that this would cause issues.<br />
  Would it be safe to assume that it's only unsafe to use <a href="https://hackage.haskell.org/package/websockets-0.12.7.3/docs/Network-WebSockets.html#v:sendTextData" rel="nofollow noreferrer">sendTextData</a> from more than one thread?</p>
  <p>In my actual backend server, I'm creating 3 threads per connection:</p>
  <ul>
  <li>Ping thread via <a href="https://hackage.haskell.org/package/websockets-0.12.7.3/docs/Network-WebSockets.html#v:withPingThread" rel="nofollow noreferrer">withPingThread</a></li>
  <li>&quot;Consumer&quot; thread, where it polls with <code>receiveData</code> like the above example</li>
  <li>&quot;Producer&quot; thread, where it polls from a <code>TQueue</code> of messages for a given connection, and sends the message via <code>sendTextData</code>.
  This thread is to allow multiple threads to queue up messages for a single connection, while only a single thread (this thread) sends text data to the client (except for the fact that receiveData can send text data as well, from the consumer thread).</li>
  </ul>
  <p>Is there any obvious mistakes with my approach?</p>