Memory access violation with channels and native library

I have trouble using std::sync::mpsc::channel in a callback from a native library.
The native library calls the same callback from multiple threads. The callback is a Rust closure that puts the data on a channel. When the sender is invoked a memory access violation happen in rustlib\src\rust\library\std\src\sync\mpsc\

I've written an isolated example of the issue:

You can start program with: cargo run --example testme

This is using rustc 1.47.0 (18bf6b4f0 2020-10-07)

Do you have any idea what may be wrong? Am I using the library wrong?

Your function is wrong. To fix it, update the where bound to this:

pub fn register_callback_safe<C>(mut c: C)
    C: Fn(String) + Send + Sync,

Then the compiler will catch the unsoudness. The issue is that the mpsc Sender is not Sync, so calling methods on it concurrently from multiple threads is not safe.

The crossbeam channel doesn't have this limitation.


Thank you for the feedback.

I updated the example with the crossbeam channel and added the Send and Sync marker traits, but I still get an access violation error (in the crossbeam code):

I'm new to Rust so I do not have in depth knowledge about how channel/crossbeam works.
But could it be that the crossbeam library do not support the same sender instance being called from multiple threads that is not provided by Rust?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.