How to Use Serial Port in Multiple Threads in Rust?












0















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.



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.



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:



let mut port = serial::open(&device_path.as_os_str()).unwrap();
let request_temperature: Vec<u8> = vec![0xAA];

thread::spawn(|| {
let mut buffer: Vec<u8> = Vec::new();
loop {
let _bytes_read = port.read(&mut buffer);
// process data
thread::sleep(Duration::from_millis(100));
}
});

loop {
port.write(&request_temperature);
thread::sleep(Duration::from_millis(1000));
}


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.










share|improve this question



























    0















    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.



    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.



    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:



    let mut port = serial::open(&device_path.as_os_str()).unwrap();
    let request_temperature: Vec<u8> = vec![0xAA];

    thread::spawn(|| {
    let mut buffer: Vec<u8> = Vec::new();
    loop {
    let _bytes_read = port.read(&mut buffer);
    // process data
    thread::sleep(Duration::from_millis(100));
    }
    });

    loop {
    port.write(&request_temperature);
    thread::sleep(Duration::from_millis(1000));
    }


    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.










    share|improve this question

























      0












      0








      0








      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.



      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.



      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:



      let mut port = serial::open(&device_path.as_os_str()).unwrap();
      let request_temperature: Vec<u8> = vec![0xAA];

      thread::spawn(|| {
      let mut buffer: Vec<u8> = Vec::new();
      loop {
      let _bytes_read = port.read(&mut buffer);
      // process data
      thread::sleep(Duration::from_millis(100));
      }
      });

      loop {
      port.write(&request_temperature);
      thread::sleep(Duration::from_millis(1000));
      }


      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.










      share|improve this question














      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.



      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.



      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:



      let mut port = serial::open(&device_path.as_os_str()).unwrap();
      let request_temperature: Vec<u8> = vec![0xAA];

      thread::spawn(|| {
      let mut buffer: Vec<u8> = Vec::new();
      loop {
      let _bytes_read = port.read(&mut buffer);
      // process data
      thread::sleep(Duration::from_millis(100));
      }
      });

      loop {
      port.write(&request_temperature);
      thread::sleep(Duration::from_millis(1000));
      }


      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.







      rust serial-port borrow-checker






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 23 '18 at 3:27









      Shane SnoverShane Snover

      311




      311
























          1 Answer
          1






          active

          oldest

          votes


















          2














          You can wrap your port in a Arc and a Mutex, then you can write something like:



          use std::sync::{Arc, Mutex};
          use std::thread;
          use std::time::Duration;

          struct Port;
          impl Port {
          pub fn read(&mut self, _v: &mut Vec<u8>) {
          println!("READING...");
          }
          pub fn write(&mut self, _v: &Vec<u8>) {
          println!("WRITING...");
          }
          }

          pub fn main() {
          let mut port = Arc::new(Mutex::new(Port));
          let p2 = port.clone();

          let handle = thread::spawn(move || {
          let mut buffer: Vec<u8> = Vec::new();
          for j in 0..100 {
          let _bytes_read = p2.lock().unwrap().read(&mut buffer);
          thread::sleep(Duration::from_millis(10));
          }
          });

          let request_temperature: Vec<u8> = vec![0xAA];
          for i in 0..10 {
          port.lock().unwrap().write(&request_temperature);
          thread::sleep(Duration::from_millis(100));
          }

          handle.join();
          }


          So that this will run on a test machine, I've replaced the serial port with a stub class, reduced the sleeps and replaced the infinite loop with some finite loops.



          While this works, you'll probably actually want proper communication between the threads at some stage, at which point you'll want to look at std::sync::mpsc::channel






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53440321%2fhow-to-use-serial-port-in-multiple-threads-in-rust%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            You can wrap your port in a Arc and a Mutex, then you can write something like:



            use std::sync::{Arc, Mutex};
            use std::thread;
            use std::time::Duration;

            struct Port;
            impl Port {
            pub fn read(&mut self, _v: &mut Vec<u8>) {
            println!("READING...");
            }
            pub fn write(&mut self, _v: &Vec<u8>) {
            println!("WRITING...");
            }
            }

            pub fn main() {
            let mut port = Arc::new(Mutex::new(Port));
            let p2 = port.clone();

            let handle = thread::spawn(move || {
            let mut buffer: Vec<u8> = Vec::new();
            for j in 0..100 {
            let _bytes_read = p2.lock().unwrap().read(&mut buffer);
            thread::sleep(Duration::from_millis(10));
            }
            });

            let request_temperature: Vec<u8> = vec![0xAA];
            for i in 0..10 {
            port.lock().unwrap().write(&request_temperature);
            thread::sleep(Duration::from_millis(100));
            }

            handle.join();
            }


            So that this will run on a test machine, I've replaced the serial port with a stub class, reduced the sleeps and replaced the infinite loop with some finite loops.



            While this works, you'll probably actually want proper communication between the threads at some stage, at which point you'll want to look at std::sync::mpsc::channel






            share|improve this answer






























              2














              You can wrap your port in a Arc and a Mutex, then you can write something like:



              use std::sync::{Arc, Mutex};
              use std::thread;
              use std::time::Duration;

              struct Port;
              impl Port {
              pub fn read(&mut self, _v: &mut Vec<u8>) {
              println!("READING...");
              }
              pub fn write(&mut self, _v: &Vec<u8>) {
              println!("WRITING...");
              }
              }

              pub fn main() {
              let mut port = Arc::new(Mutex::new(Port));
              let p2 = port.clone();

              let handle = thread::spawn(move || {
              let mut buffer: Vec<u8> = Vec::new();
              for j in 0..100 {
              let _bytes_read = p2.lock().unwrap().read(&mut buffer);
              thread::sleep(Duration::from_millis(10));
              }
              });

              let request_temperature: Vec<u8> = vec![0xAA];
              for i in 0..10 {
              port.lock().unwrap().write(&request_temperature);
              thread::sleep(Duration::from_millis(100));
              }

              handle.join();
              }


              So that this will run on a test machine, I've replaced the serial port with a stub class, reduced the sleeps and replaced the infinite loop with some finite loops.



              While this works, you'll probably actually want proper communication between the threads at some stage, at which point you'll want to look at std::sync::mpsc::channel






              share|improve this answer




























                2












                2








                2







                You can wrap your port in a Arc and a Mutex, then you can write something like:



                use std::sync::{Arc, Mutex};
                use std::thread;
                use std::time::Duration;

                struct Port;
                impl Port {
                pub fn read(&mut self, _v: &mut Vec<u8>) {
                println!("READING...");
                }
                pub fn write(&mut self, _v: &Vec<u8>) {
                println!("WRITING...");
                }
                }

                pub fn main() {
                let mut port = Arc::new(Mutex::new(Port));
                let p2 = port.clone();

                let handle = thread::spawn(move || {
                let mut buffer: Vec<u8> = Vec::new();
                for j in 0..100 {
                let _bytes_read = p2.lock().unwrap().read(&mut buffer);
                thread::sleep(Duration::from_millis(10));
                }
                });

                let request_temperature: Vec<u8> = vec![0xAA];
                for i in 0..10 {
                port.lock().unwrap().write(&request_temperature);
                thread::sleep(Duration::from_millis(100));
                }

                handle.join();
                }


                So that this will run on a test machine, I've replaced the serial port with a stub class, reduced the sleeps and replaced the infinite loop with some finite loops.



                While this works, you'll probably actually want proper communication between the threads at some stage, at which point you'll want to look at std::sync::mpsc::channel






                share|improve this answer















                You can wrap your port in a Arc and a Mutex, then you can write something like:



                use std::sync::{Arc, Mutex};
                use std::thread;
                use std::time::Duration;

                struct Port;
                impl Port {
                pub fn read(&mut self, _v: &mut Vec<u8>) {
                println!("READING...");
                }
                pub fn write(&mut self, _v: &Vec<u8>) {
                println!("WRITING...");
                }
                }

                pub fn main() {
                let mut port = Arc::new(Mutex::new(Port));
                let p2 = port.clone();

                let handle = thread::spawn(move || {
                let mut buffer: Vec<u8> = Vec::new();
                for j in 0..100 {
                let _bytes_read = p2.lock().unwrap().read(&mut buffer);
                thread::sleep(Duration::from_millis(10));
                }
                });

                let request_temperature: Vec<u8> = vec![0xAA];
                for i in 0..10 {
                port.lock().unwrap().write(&request_temperature);
                thread::sleep(Duration::from_millis(100));
                }

                handle.join();
                }


                So that this will run on a test machine, I've replaced the serial port with a stub class, reduced the sleeps and replaced the infinite loop with some finite loops.



                While this works, you'll probably actually want proper communication between the threads at some stage, at which point you'll want to look at std::sync::mpsc::channel







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 25 '18 at 14:47









                Shepmaster

                153k14300437




                153k14300437










                answered Nov 23 '18 at 4:56









                Michael AndersonMichael Anderson

                45.3k695148




                45.3k695148






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53440321%2fhow-to-use-serial-port-in-multiple-threads-in-rust%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    To store a contact into the json file from server.js file using a class in NodeJS

                    Redirect URL with Chrome Remote Debugging Android Devices

                    Dieringhausen