Estoy leyendo http://www.mono-project.com/ThreadsBeginnersGuide.C# Enhebrado: una condición de carrera ejemplo
El primer ejemplo tiene el siguiente aspecto:
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);
}
}
}
Salida:
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
Wow, ¿qué es esto? Desafortunadamente, la explicación en el artículo es inadecuada para mí. ¿Puede explicarme por qué los incrementos ocurrieron en una orden desordenada?
Gracias!
El autor del artículo mencionado dice que la salida "puede" ser como se muestra. Esto es cierto en el sentido de que no se puede probar que la salida no sea como se muestra. Sin embargo, en la práctica dado que a First se le da aproximadamente una ventaja inicial de 10 ms, esperaría ver alternancia de paso de bloqueo durante bastantes iteraciones antes de que ocurra cualquier "confuso". –