mogo
mogo

Reputation: 440

Adding integers concurrently with relevant ordering does not work as expected

In one of his great video, Jon Gjengset implements a mutex to notably understand the effect of std::sync::atomic::Ordering. The code is very simple : create a mutex that holds an integer and start many threads to add 1 to the integer concurrently and see the results. The code is here (I reproduce stricly Jon example) : https://github.com/fmassot/atomics-rust

When using correct ordering, we expect the program to make additions atomically and check the result as the sum of all added values. The code does several times on each thread the following actions :

Unfortunately it does not seem to work on linux/x86_64 nor on macbook/arm64.

The results when running cargo r --release are sometimes correct, sometimes wrong like this:

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `985`,
 right: `1000`', src/main.rs:58:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
I put the code here https://github.com/fmassot/atomics-rust

Currently I don't understand why the current implementation is not working, I'm quite new in rust and it may either come from a stupid error from me or something more subtle.

Thanks for you help!

Upvotes: 1

Views: 70

Answers (1)

mogo
mogo

Reputation: 440

Problem solved, solution given by @user4815162342

The same value was used for LOCKED and UNLOCKED so there was no lock at all.

Conclusion, the error was stupid and coming from me...

Upvotes: 0

Related Questions