title: How to Use Serial Port in Multiple Threads in Rust?
body: <p>I am trying to read and write to my serial port on Linux to communicate with a microcontroller and I'm trying to do so in Rust.</p>
  
  <p>My normal pattern when developing in say C++ or Python is to have two threads: one which sends requests out over serial periodically and one which reads bytes out of the buffer and handles them.</p>
  
  <p>In Rust, I'm running into trouble with the borrow checker while using the serial crate. This makes sense to me why this is, but I'm unsure what designing for an asynchronous communication interface would look like in Rust. Here's a snippet of my source:</p>
  
  <pre><code>let mut port = serial::open(&amp;device_path.as_os_str()).unwrap();
  let request_temperature: Vec&lt;u8&gt; = vec![0xAA];
  
  thread::spawn(|| {
      let mut buffer: Vec&lt;u8&gt; = Vec::new();
      loop {
          let _bytes_read = port.read(&amp;mut buffer);
          // process data
          thread::sleep(Duration::from_millis(100));
      }
  });
  
  loop {
      port.write(&amp;request_temperature);
      thread::sleep(Duration::from_millis(1000));
  }
  </code></pre>
  
  <p>How can I emulate this functionality where I have two threads holding onto a mutable resource in Rust? I know that since this specific example could be done in a single thread, but I'm thinking for an eventual larger program this would end up being multiple threads.</p>