Joe Albahari가 C#의 volatile
을 설명하는 아주 좋은 기사가 있습니다 : Threading in C#: PART 4: ADVANCED THREADING.휘발성 읽기/쓰기 및 명령 순서 재 지정
public class IfYouThinkYouUnderstandVolatile
{
private volatile int x, y;
private void Test1() // Executed on one thread
{
this.x = 1; // Volatile write (release-fence)
int a = this.y; // Volatile read (acquire-fence)
}
private void Test2() // Executed on another thread
{
this.y = 1; // Volatile write (release-fence)
int b = this.x; // Volatile read (acquire-fence)
}
}
기본적으로 그가 말하는 것은 a
및 b
두 방법은 병렬로 다른 스레드에서 실행중인 경우 0
를 포함 끝낼 수 있다는 것입니다 :
고려 명령 재정렬 조이 예제를 사용합니다.
IOW 최적화 또는 다음과 같이 명령을 다시 정렬 할 수 프로세서 : 우리가 volatile
를 사용하고 있지만 이런 일이 왜
public class IfYouThinkYouUnderstandVolatileReordered
{
private volatile int x, y;
private void Test1() // Executed on one thread
{
int tempY = this.y; // Volatile read (reordered)
this.x = 1; // Volatile write
int a = tempY; // Use the already read value
}
private void Test2() // Executed on another thread
{
int tempX = this.x; // Volatile read (reordered)
this.y = 1; // Volatile write (release-fence)
int b = tempX; // Use the already read value
}
}
이유는 가 이동할 수있는 쓰기 명령 다음 명령을 읽을 수 있다는 것입니다 쓰기 지침 전에.
지금까지 나는 여기서 무슨 일이 일어나고 있는지 이해하고 있습니다.
내 질문 : 스택 프레임을 통해 재주문이 가능합니까? 다른 방법 (또는 속성 접근 자)에서 일어나는 휘발성 읽기 명령어 다음에 휘발성 쓰기 명령어를 옮길 수 있습니까?
다음 코드를 살펴보십시오. 인스턴스 변수에 직접 액세스하는 대신 속성을 사용하고 있습니다.
이 경우 재정렬은 어떻게됩니까? 어쨌든 일어날 수 있을까요? 또는 속성 액세스가 컴파일러에 의해 인라인 될 경우에만 발생할 수 있습니까?
public class IfYouThinkYouUnderstandVolatileWithProps
{
private volatile int x, y;
public int PropX
{
get { return this.x; }
set { this.x = value; }
}
public int PropY
{
get { return this.y; }
set { this.y = value; }
}
private void Test1() // Executed on one thread
{
this.PropX = 1; // Volatile write (release-fence)
int a = this.PropY; // Volatile read (acquire-fence)
}
private void Test2() // Executed on another thread
{
this.PropY = 1; // Volatile write (release-fence)
int b = this.PropX; // Volatile read (acquire-fence)
}
}
휘발성은 모두 멈추지 않습니다 ** 모든 ** 재주문이 키워드를 사용하면 같은 유형의 작업을 다시 정렬 할 수 있습니다 (쓰기 전에 두 가지 읽기와 두 번 읽는 것). – VMAtm