title: Killing a thread when MVar is garbage collected
body: <p>I have a worker thread which reads data repeatedly from an MVar and performs some useful work on that. After a while, the rest of the program forgets about that worker thread, which means that it will wait on an empty MVar and become very lonely. My question is:</p>
  
  <blockquote>
    <p>Will the MVar be garbage collected if threads no longer write to it, for instance because they all wait for it?
    Will garbage collection kill the waiting threads?
    If neither, can I somehow indicate to the compiler that the MVar should be garbage collected and the thread be killed?</p>
  </blockquote>
  
  <p><strong>EDIT:</strong> I should probably clarify the purpose of my question. I don't desire general protection against deadlocks; instead, what I would like to do is to tie the life of the worker thread to life of a value (as in: dead values are claimed by garbage collection). In other words, the worker thread is a resource that I would like to free not by hand, but when a certain value (the MVar or a derivative) is garbage collected.</p>
  
  <p><br></p>
  
  <p>Here an example program that demonstrates what I have in mind</p>
  
  <pre><code>import Control.Concurrent
  import Control.Concurrent.MVar
  
  main = do
      something
      -- the thread forked in  something  can  be killed here
      -- because the  MVar  used for communication is no longer in scope
      etc
  
  something = do
      v &lt;- newEmptyMVar
      forkIO $ forever $ work =&lt;&lt; takeMVar v
      putMVar v "Haskell"
      putMVar v "42"
  </code></pre>
  
  <p>In other words, I want the thread to be killed when I can no longer communicate with it, i.e. when the MVar used for communication is no longer in scope. How to do that?</p>