sinshu / rustysynth

A SoundFont MIDI synthesizer written in pure Rust
Other
108 stars 20 forks source link

Use Arcs instead of Rcs to enable using multiple threads #5

Closed sapir closed 1 year ago

sapir commented 1 year ago

Hi, this allows using rustysynth for live synthesis with rodio, which requires the audio sources to be Send.

Thank you for making this library!

sinshu commented 1 year ago

Thanks for the PR 😄

I was researching multithreading in Rust and found the following article: https://www.sobyte.net/post/2022-02/rust-mutex-send/

So, does this mean that Synthesizer has an internal Rc and passing it to another thread will result in an error? I didn't want to put any code in the library that anticipated multithreading, but I feel that Arc is indeed the only way to go here 🤔

sapir commented 1 year ago

It makes sense that you can't pass an Rc to a different thread, because even though you own the Rc that you're sending, there might still be other Rcs referencing the same object, so you would end up with the object being accessible with Rcs from different threads. For example:

let rc1 = Rc::new("this is some data".to_string());
let rc2 = Rc::clone(&rc1);
std::thread::spawn(move || {
    // We can use the string in rc1 here
    println!("rc1 is {}", rc1);
});
// We can use the same string in rc2 here
println!("rc2 is {}", rc2);