problem in peterson's lock in shared memory
I have开发者_如何学C implemented peterson' algorithm for mutual exclusion in shared memory. I am using shared memory between a c++ and a java process(using jni) for communication. The problem is that I am still seeing a race condition somehow. If I try to debug it using printf/println, the code starts running fine, but as soon as I remove those prints the processes stall. Can somebody please enlighten me where could be the problem? I am quite sure that the implementation of peterson's algorithm is correct. Should I use semaphores(semget()) instead for mutual exclusion?
To implement the algorithm properly you must use barriers to ensure that the memory is read/written in the order you specify in the code. Read the second paragraph from here:
Most modern CPUs reorder memory accesses to improve execution efficiency (see memory ordering for types of reordering allowed). Such processors invariably give some way to force ordering in a stream of memory accesses, typically through a memory barrier instruction. Implementation of Peterson's and related algorithms on processors which reorder memory accesses generally requires use of such operations to work correctly to keep sequential operations from happening in an incorrect order. Note that reordering of memory accesses can happen even on processors that don't reorder instructions (such as the PowerPC processor in the Xbox 360).
And yes, use the synchronization mechanisms provided by the system (mutexes) instead of reinventing the wheel.
I think your problem would be related to not mutual exclusion but sycronyzation. Peterson algorithm only secures one process to be in critical region and doesn't secure which processes should be in critical region. If your problem is right what I mention, I suggest to use Moniter as sycronyzing.
There should be some critical section in your code that is shared by both the process. When you run the program without lock, the output will be different and ambiguous hence we can verify if your code is working.
The problem is that you are using print statement and when you remove them there should be something shared.
Can you share the what logic you are using to PETERSON’S ALGORITHM
Visit : Peterson Algorithm
精彩评论