Skip to content

Instantly share code, notes, and snippets.

@rofr
Last active December 24, 2015 08:39
Show Gist options
  • Save rofr/6772292 to your computer and use it in GitHub Desktop.
Save rofr/6772292 to your computer and use it in GitHub Desktop.
Immutability code for informatorbloggen
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