c++ - CPU instruction reordering -
our processors allowed reorder instruction in order gain performance benefits, may cause strange behaviour. i'm trying reproduce 1 of issues on base of this article.
this code:
int a,b; int r1,r2; mutex m1,m2; void th1() { for(;;) { m1.lock(); a=1; asm volatile("" ::: "memory"); r1=b; m1.unlock(); } } void th2() { for(;;) { m2.lock(); b=1; asm volatile("" ::: "memory"); r2=a; m2.unlock(); } } int main() { int cnt{0}; thread thread1{th1}; thread thread2{th2}; thread1.detach(); thread2.detach(); for(int i=0;i<10000;i++) { m1.lock(); m2.lock(); a=b=0; m1.unlock(); m2.unlock(); if(r1==0&&r2==0) { ++cnt; } } cout<<cnt<<" cpu reorders happened!\n"; }
i use mutexes sure 'main' thread not modify nor b when th1 or th2 doing jobs, output of execution change time, may 0, may 10000 or casual number between 0 , 10000.
there's code makes me little unconfortable, i'm not sure whether reproduce cpu reordering phenomen.
from code looks way r1 , r2 may 0 in 'if' because of th1 , th2 set them value 'a' , 'b', in context of th1 , th2 cannot 0 due lock mechanism, way variables 0 because of instruction reordering, this correct?
thanks
your program different 1 in article cited preshing.com. preshing.com program uses semaphores yours uses mutexes.
mutexes simpler semaphores. make 1 guarantee--that 1 thread @ time can lock mutex. say, can used mutual exclusion.
the preshing.com program semaphores can't mutexes alone: synchronizes loops in 3 threads proceed in lock-step. thread1 , thread2 each wait @ top of loop until main() lets them go, , main waits @ bottom of loop until have completed work. go 'round again.
you can't mutexes. in program, prevents main going around loop thousands of times before either of other 2 threads gets run @ all? nothing chance. nor prevent thread1 and/or thread2 looping thousands of times while main() blocked, waiting next time slice.
remember, semaphore counter. @ how semaphores in preshing.com incremented , decremented threads, , see how keeps threads synchronized.
Comments
Post a Comment