Last active
December 24, 2015 08:39
-
-
Save rofr/6772292 to your computer and use it in GitHub Desktop.
Immutability code for informatorbloggen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void Main(string[] args) | |
{ | |
string[] input = {"Ramy", "Gregory", "Willstrop", | |
"Matthew", "El Shorbagy", "Drakenberg", "Hult", "Friberg"}; | |
var players = new ImmutableList<SquashPlayer>(); | |
var rnd = new Random(); | |
var writer = new Thread( () => { | |
int i = 1; | |
foreach(string name in input) | |
{ | |
var player = new SquashPlayer(name, i++); | |
players = players.Add(player); //tilldelning är en atomär operation | |
Thread.Sleep(rnd.Next(1000)); | |
} | |
}); | |
var reader = new Thread( () => { | |
for(int i = 0; i < 1000000; i++) | |
{ | |
int rankingSum = 0; | |
var playersRef = players; //läser en ögonblicksbild av en omutbar lista | |
int count = players.Count; | |
foreach(var player in playersRef) rankingSum += player.Ranking; | |
Debug.Assert((1 + count)/2.0*count == rankingSum); | |
} | |
}); | |
writer.Start(); | |
reader.Start(); | |
writer.Join(); | |
reader.Join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment