Yes, the code may behave non-deterministally due to various factors, such as timing details at the hardware level, implementation details in the OS's scheduling algorithm, etc. This causes var to be incremented by random amounts each time through the loop. The usage of std::atomic guarantees that var will always be read and updated in a
consistent manner (i.e. never being half-updated).
"Non-deterministic" doesn't even imply "concurrent", so there's a chance that OP won't (or possibly can't) get what he asked for. |
I have no idea what you're talking about.
Yes, non-determinism doesn't imply concurrency, but threads are both concurrent and parallel.
OP didn't imply he wanted deterministic behavior, but if he does, his question is underspecified.
[quote]I doubt that concurrency is what OP needs[/qoute]Doing one thing "while also" doing another is the definition of concurrency.
Modelling deterministic concurrency, while possible, is in the general case far more complicated.
For example in OP's example, to concurrently and deterministically increment a variable while a loop runs, it might be sufficient to do this:
1 2 3 4
|
while (/*...*/){
f();
var++;
}
|
Or this:
1 2 3 4
|
while (/*...*/){
f();
var += step;
}
|
Or even:
1 2 3 4 5 6 7
|
while (/*...*/){
f();
if (++var2 == step2){
var += step;
var2 = 0;
}
}
|
But things get really complicated really fast:
1 2 3 4
|
while (/*...*/){
f();
g();
}
|
How do you coordinate concurrent state changes by the two functions? This is a rabbit hole that goes really deep, up to and including implementing a virtual machine where instructions run atomically.