++counter ;
if(counter == MAXIMUM_NUM){
// some procedure is done if counter
// was equal to MAXIMUM_NUM when it was tested in the if condition
// (we can't assume that counter would still be equal to MAXIMUM_NUM at this point)
}
I apologize for my poor explanation of my conditions.
As my intention, when the above procedures just are called MAXIMUM_NUM times, the thread is expected to enter the scope in the if statement.
(If I am wrong, I am sorry) in your code, 1 line is not atomic operation so that when some threads simultaneously process the line, counter is not correctly incremented.
On the other hand, in my code, one thread first processes the counter increment, and then, before if condition is evaluated, other thread processes the counter increment, which fails my intended code behavior.
You use the result returned by whatever method you choose.
You can't increment and examine counter directly in two separate statements and expect success.
1 2 3 4 5 6 7 8 9
atomic<int> counter;
///
int t = ++counter;
if ( t == MAXIMUM_NUM ) {
// if you still need counter == MAXIMUM_NUM here, then
// you need a mutex
}
> one thread first processes the counter increment, and then,
> before if condition is evaluated, other thread processes the counter increment
To avoid that, this could be done:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <atomic>
constexprint MAXIMUM_NUM = 10 ;
std::atomic<int> counter{0};
void foo()
{
if( ++counter == MAXIMUM_NUM ) {
// some procedure is done if value of counter after increment was equal to 10
}
}