• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to develop a solution for critical section  RSS feed

 
Micheal H Nguyen
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let say we have an atomic function Compare-and-Swap:
CSW(a,b,c)<
if (a==c){
c = b; return 0;
}else { a = c; return 1;}>
How do we use this CSW(a,b,c) to develop a solution to the critical section problem for n threads?
Thank you
 
Henry Wong
author
Sheriff
Posts: 23280
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A CAS (compare and set) operator is built into the instruction set of almost every processor today (in some form or another). It is atomic. And it is use to implement the basic mutex (synchronization) funntionality.

This is probably a standard homework question for a computer architecture class, so I'll stop here. How do you think it works? Given the capability to conditionally set or swap a value, based on its current value, how would you implement synchronization?


BTW, as a side note, the Java Virtual Machine actually doesn't have a CAS in its instruction set. Instead, it implements the higher level monitor in and out (synchronization) directly. I guess this is so that it can do synchronization with one bytecode instruction.

Unfortunately, without a CAS, you have to rely on synchronization for everything, making it impossible to code optimistically. This is why they added the Atomic Variables in Java 5 -- this is basically a set of variables that implements a form of CAS (obviously using JNI under the covers to get to the CAS operator).

Henry
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!