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\mod.rs(767).

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)
where
    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.

3 Likes

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):
rustlib\src\rust\library\core\src\sync\atomic.rs(2370)

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?