// C5 example: locking 2005-11-07 // Compile with // csc /r:C5.dll Locking.cs using System; using System.Threading; using C5; using SCG = System.Collections.Generic; namespace Locking { class Locking { static ArrayList coll = new ArrayList(); // static SCG.List coll = new SCG.List(); static readonly int count = 1000; public static void Main(String[] args) { Console.WriteLine("Adding and removing without locking:"); RunTwoThreads(delegate { AddAndRemove(15000); }); Console.WriteLine("coll has {0} items, should be 0", coll.Count); coll = new ArrayList(); Console.WriteLine("Adding and removing with locking:"); RunTwoThreads(delegate { SafeAddAndRemove(15000); }); Console.WriteLine("coll has {0} items, should be 0", coll.Count); Console.WriteLine("Moving items without locking:"); ArrayList from, to; from = new ArrayList(); to = new ArrayList(); for (int i=0; i(); to = new ArrayList(); for (int i=0; i(IExtensible coll, T x) { lock (sync) { coll.Add(x); } } public static void Move(ICollection from, ICollection to) { if (!from.IsEmpty) { T x = from.Choose(); Thread.Sleep(0); // yield processor to other threads from.Remove(x); to.Add(x); } } public static void SafeMove(ICollection from, ICollection to) { lock (sync) if (!from.IsEmpty) { T x = from.Choose(); Thread.Sleep(0); // yield processor to other threads from.Remove(x); to.Add(x); } } } }