나는 http://www.mono-project.com/ThreadsBeginnersGuide을 읽고 있습니다.C# 스레딩 : 경쟁 조건 예제
첫 번째 예는 다음과 같습니다 출력
public class FirstUnsyncThreads {
private int i = 0;
public static void Main (string[] args) {
FirstUnsyncThreads myThreads = new FirstUnsyncThreads();
}
public FirstUnsyncThreads() {
// Creating our two threads. The ThreadStart delegate is points to
// the method being run in a new thread.
Thread firstRunner = new Thread (new ThreadStart (this.firstRun));
Thread secondRunner = new Thread (new ThreadStart (this.secondRun));
// Starting our two threads. Thread.Sleep(10) gives the first Thread
// 10 miliseconds more time.
firstRunner.Start();
Thread.Sleep (10);
secondRunner.Start();
}
// This method is being excecuted on the first thread.
public void firstRun() {
while(this.i < 10) {
Console.WriteLine ("First runner incrementing i from " + this.i +
" to " + ++this.i);
// This avoids that the first runner does all the work before
// the second one has even started. (Happens on high performance
// machines sometimes.)
Thread.Sleep (100);
}
}
// This method is being excecuted on the second thread.
public void secondRun() {
while(this.i < 10) {
Console.WriteLine ("Second runner incrementing i from " + this.i +
" to " + ++this.i);
Thread.Sleep (100);
}
}
}
:
First runner incrementing i from 0 to 1
Second runner incrementing i from 1 to 2
Second runner incrementing i from 3 to 4
First runner incrementing i from 2 to 3
Second runner incrementing i from 5 to 6
First runner incrementing i from 4 to 5
First runner incrementing i from 6 to 7
Second runner incrementing i from 7 to 8
Second runner incrementing i from 9 to 10
First runner incrementing i from 8 to 9
와우,이게 뭐죠? 불행히도, 기사의 설명은 나를 위해 부적절합니다. 뒤죽박죽 순서로 증분이 왜 발생했는지 설명해 주시겠습니까?
감사합니다.
언급 된 기사의 저자는 출력이 "표시 될 수 있습니다"라고 말합니다. 이는 출력이 표시되지 않았 음을 증명할 수 없다는 점에서 사실입니다. 그러나 실제로는 First가 약 10ms의 헤드 스타트를 받았다면, "뒤죽박죽"이 발생하기 전에 꽤 많은 반복 동안 락 스텝 변경이 일어날 것으로 예상 할 수 있습니다. –