2 ms·
What do you mean by “on the same memory” exactly? If you want two threads running in parallel to concurrently access the same memory location you don't need sy
by littlestymaar 7y ago
What do you mean by “on the same memory” exactly?
If you want two threads running in parallel to concurrently access the same memory location you don't need synchronization if you only perform reads, and you need one if there is at least one write. Like in any other language (this comes directly from how CPU works).
The good thing with Rust is that you can't shoot yourself in the foot: if you can't accidentally have an unsynchronize mutable variable accessible from two threads: the compiler will show you an error (unless you explicitely opt out this security by using unsafe primitives, in which case the borrow checker will let you go).
- bullen 7y agoI mean just like it reads: I want two (or more) threads to write the same memory at the same time. This is a problem Java "solved"/"worked around" with a complete memory model rewrite for the whole JDK and the concurrency package in 2004 (1.5). The solutions range from mutexes to copy-on-write and more.
- oconnor663 7y agoMy understanding is that Rust is basically equivalent to C in this regard, in terms of concurrent writes to the same memory being per se undefined behavior. I think the JVM translates concurrent memory writes into hardware-appropriate atomics, so maybe a better translation from Java to Rust would be a large `Vec<AtomicUsize>` or something like that, rather than raw memory?
- unlinked_dll 7y agoyou can use whatever synchronization techniques you want, from lock free data structures/queues, to mutexes, to unadulterated unsafe reads/writes to raw pointers. std provides some useful helpers like Arc and Mutex (Arc<Mutex<Type>> is always safe to use across threads, as the lifetime is managed safely by Arc and accesses handled by Mutex). There are crates out there for things like lock free sync and other GC if you need it. Rust doesn't force you into a single world view.