On Apr 4, 1:53?pm, Bart van Ingen Schenau
It would be if you prove that according to the standard C++11 abstract
machine cannot deadlock, say, on two threads executing
thread 1:
m1.lock();
m1.unlock();
m2.lock();
m2.unlock();
thread 2:
m2.lock();
m2.unlock();
m1.lock();
m1.unlock();
Yes, I know, if this code is executed "sequentially" it cannot
deadlock, but I mean C++11 abstract machine
The lock and unlock MAY be reordered, but only if the compiler can prove
that the execution of the reordered code yields the same observable
behavior as the non-reordered code would yield in the (concurrent)
abstract machine.
I am not completely sure you are right here, saying that non-reordered
code execution is what defines the execution of abstract machine. Here
is example of program which can not deadlock if executed in "ordered"
way, but might deadlock if executed with reordering. And I suppose you
should agree that BOTH executions are what the standard allows, i.e.
they should both conform to the abstract machine.
thread 1:
// atomic1 and atomic2 are initially 0 (zero)
atomic1.store(1, memory_order_relaxed);
atomic2.store(2, memory_order_relaxed);
thread2:
int a2 = atomic2.load(memory_order_seq_cst);
int a1 = atomic1.load(memory_order_seq_cst);
if(a2==2 && a1==0)
GO_AND_DEADLOCK_OUR_PROGRAM(); // never returns,
// blocks all threads
))
thread2 will execute GO_AND_DEADLOCK_OUR_PROGRAM() only if assignments
to atomic1 and atomic2 in thread1 were reordered by compiler (hardware
reordering aside). And such execution is allowed by standard!
If the reordering introduces a deadlock that is not present in the
original program, then the observable behavior would change (non-
termination versus termination of the program).
That is what you see in my last example. Ordered execution does not
deadlock. Reordered execution deadlocks. Both executions are allowed
for observable behavior of abstract machine.
Now if you agree with this, then probably your argument is not enough
to explain why mutex operations cannot be reordered.
If the mutex is implemented using volatile objects, then the reordering
is prohibited on the grounds that it would affect the order in which
volatile objects are accessed.
Yes. And no, as hardware may still reorder accesses to volatiles. But
I am not talking about volatiles here. And mutexes are not supposed to
be based on volatile operations.
Regards, Michael