title: Background worker thread and synchronization in Rust
body: <p>I'm trying to write a simple library that has a background worker thread that processes commands when the library functions are called. </p>
  
  <p>The way that I would normally do it in C is have a global semaphore handle that the worker would block on. The functions would give the semaphore after they sent a command, at which point the worker would unblock etc... There are other ways but this is just an example.</p>
  
  <p>I have a few questions about how I can achieve something similar with Rust. </p>
  
  <ol>
  <li><p>How do I prevent a thread from closing once the function that created it returns? e.g the thread would be created when I call <code>init()</code>, but would exit when <code>init()</code> returns, how to prevent this?</p></li>
  <li><p>How to have a have a global synchronization method between the worker thread and function calls? I was looking at using channels but how do I access the <code>rx</code> from the thread and multiple <code>tx</code>'s from different functions? e.g <code>send_cmd_a()</code>, <code>send_cmd_b()</code> to the same thread</p></li>
  </ol>
  
  <p>Pseudo code of what I'm trying to accomplish:</p>
  
  <pre><code>static (tx, rx) = mpsc::channel(); //how to do something like this?
  
  fn init() {
      thread::spawn(|| {
          loop {
              let cmd = rx.recv().unwrap(); //blocks till there is data
                                            //process data....
              if cmd == "exit" {
                  return;
              }
          }
      });
  }
  
  fn send_cmd_a() {
      //Do a bunch of other stuff...
      tx.send("cmd_a").unwrap();
  }
  
  fn exit() {
      tx.send("exit").unwrap();
  }
  </code></pre>
  
  <p>Do I have to create one big object that encapsulates all of this, thus owning the synchronization mechanism? (still doesn't answer question #1) </p>
  
  <p>What would be the preferred way of doing something like this in Rust? </p>