3 ms·
Too late to edit the post but maybe some code sample will help illustrate the pattern. I am typing code into a web form so I make no guarantees that it is perf
by asveikau 12y ago
Too late to edit the post but maybe some code sample will help illustrate the pattern. I am typing code into a web form so I make no guarantees that it is perfect.
// Performs some modification on the input.
extern int f(int);
volatile int global_var = /* ... */;
int expected;
int new; // assuming C and not C++, where "new" is reserved
do
{
// Do a speculative read
expected = global_var;
// Make some (non-atomic) modification
new = f(expected);
// loop until the speculative read was OK. (won the race)
} while (compare_and_swap(&global_var, expected, new) != expected);
- dbaupp 12y agoWhoops, I got the signature of CAS slightly wrong. In any case, I already understood the pattern and understand why it is OK. However, as I said, it is the exception that a data race is OK, which is why Rust disallows them by default (it does not disallow them completely).