In the classic Peterson's algorithm, you check for 2 flags flag1 and flag2 and the turn variable before entering a critical section.Will this work if I check for turn first and then check for the flags ?
相关问题
- Finding k smallest elements in a min heap - worst-
- binary search tree path list
- High cost encryption but less cost decryption
- multidplyr : assign functions to cluster
- Why should we check WIFEXITED after wait in order
相关文章
- What are the problems associated to Best First Sea
- How to use doMC under Windows or alternative paral
- Coin change DP solution to keep track of coins
- Algorithm for partially filling a polygonal mesh
- Robust polygon normal calculation
- Algorithm for maximizing coverage of rectangular a
- Parallel while loop in R
- Does gfortran take advantage of DO CONCURRENT?
Yes, it will work, if you first check
turn
and then checkflag[0]
orflag[1]
inside the condition inwhile()
.The reason is that busy waiting is performed only when both conditions are true.
As a proof I've written a small C program simulating two processes with random switches between them.
For the critical section I use this piece of code in process 0:
and this in process 1:
Both processes execute this section 1000 times each. If there's a race condition between the critical sections of the two,
global
will likely be different from 2000 at the end of the simulation.Code:
Output (ideone):
Now, the same program with the order of the checks as in Wikipedia, for which I define
SWAP_CHECKS
as 0: output (ideone):Finally, to show that there's a race condition when Peterson's algorithm is disabled, I define
USE_PETERSON
as 0: output (ideone):