Poperton
Poperton

Reputation: 1808

How could Rust's channels be implemented?

I'm curious about how could someone implement a send/receive channel in Rust. Certainly some data has to be accessed by 2 threads at the same time. Otherwise, how can thread B know when a mssage from thread A arrived?

In C++, both threads access a shared queue and when one adds to a queue, it notifies a condition variable in where the other thread is waiting.

In Rust I cannot have a shared object: I can move it like it were an C++ unique_ptr, or I can pass a reference to it, but then the object is locked and the other thread can't acces it. Or can it, but only with read permissions? Even if yes, there's still a problem, it might read that variable in the middle of a write.

Upvotes: 1

Views: 885

Answers (1)

Kornel
Kornel

Reputation: 100220

For situations like this Rust has unsafe code blocks, raw C *mut pointers, and UnsafeCell wrapper type. These are low-level building blocks for creating higher-level (and safe) abstractions.

UnsafeCell informs the compiler that the memory it holds will be mutably shared by threads, and the compiler won't make it Undefined Behavior to mutate it from multiple threads. Then code can add some synchronization primitives around the cell to make it actually safe. This is the key to implementing internals of types like Atomic, Mutex, and channels.

Upvotes: 1

Related Questions