volatile keyword

Tags:

* Meaning of volatile

(1) In C: Volatile never works except for just 1 CPU environment because volatile keyword just gurantees that compiler will not reorder volatile variable. However, MMU and CPU can.

I think the only useful application of volatile in C is the interrupt handling. For example, you can declare a variable as volatile and share it between main program and interupt handler. I don’t know any other applications.

(2) In JAVA: Gurantees happens before relathionship between read and write ops. But volatile does not funtion in JDK 1.4 or before. In JDK 1.5 or later, volatile is *very* slow. (If that’s true, who the hell are you, Mr. volatile?)

In addition, in volatile of JAVA, only reads and writes are atomic. Read-modify-writes are not. For example,


// This is okay.
volatile int a=3; // volatiile a
a=5; // write is atomic. written value will be shown to other threads.
System.out.println(a); // read is atomic.

// This does not function as you expected.
volatile int b=3; // volatile b
b = b+3; // this is not thread-safe in multi-processors env.

The above statement, b=b+3, can be interpreted as:


int temp = b; // non volatile temp. this is atomic.
temp = temp+3; // this is the problem. 
               // At this time, other thread can intercept and 
               // read b value (=3).
b = temp; // this is atomic

If you want read-modify-write, you must use java.util.concurrent package.

(3) In .NET: I don’t know much about red. Microsoft.

* Any comments are welcome!

그러니까 자세한 건 모르겠고.. 더 세부적으로 알려면 밑도 끝도 없이 공부해야하는 거 같은데, 그럴 시간도 없고 흥미도 없고 해서 대강의 결론을 내리자면,

닷넷에는 메모리 베리어를 임의로 넣을 수 있단 말이죠.. 만약 volatile 이 자바와 마찬가지의 의미를 갖는다면 (즉, 컴파일러에 의한 reordering을 막으면서 동시에 메모리 베리어까지 삽입), 왜 메모리 베리어 API같은게 필요한건지 모르겠군요.. 그렇다면 다만 컴파일러에 의한 리오더링을 막는 용도로 volatile을 제공하는걸까요.. 뭐, 모르겠군요. -_-;;; (여하튼 닷넷에선 예전부터 atomic한 read-write-modify 를 위한 construct – 예를들어 1증가시키기 등의 메소드 – 를 제공해왔죠. MS가 조금만 더 오픈소스적으로 나서주면 – 가령 지들이 컴파일러를 마구 뿌린다던가 – .NET이 마구 퍼지고 그러면 저도 과감히 전향할 이유가 되서 세상 살기 더 좋을텐데요..)

역시 하이테크놀로지의 두가지 메인 언어를 다 잘하는건 미션 임파서블인 듯. 그냥 자바만으로 행복하게 살랍니다…

이 글 내용에 대한 태클 환영. Alex 아저씨는 질문하면 너무 무섭게 대답함 -_-;;;
사실 공부안하고 자꾸 물어만 봐서 미안하긴 함…

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *