public void TestParallelAmr() { var random = new Random((int)DateTime.Now.Ticks & 0x0000ffff); for (var j = 0; j < 50; j++) { var orders = new HashedMap <Order, bool>(10, new OrderEqualityComparer()); var orderRef = new Order { Id = -1, Name = "-1" }; var markedOrder = new AtomicMarkableReference <Order>(orderRef, false); for (var i = 0; i < 10; i++) { var order = new Order { Id = i, Name = i.ToString() }; var marked = (random.Next() % 2) == 1; orders.Add(order, marked); } var results = new bool[10]; Parallel.ForEach(orders, x => { var rand = 0; lock (locker) { rand = random.Next() % 20; } Thread.Sleep(rand); var result = markedOrder.CompareExchange(orderRef, false, x.Key, x.Value); lock (locker) { results[x.Key.Id] = result; } }); Assert.Equal(orders[markedOrder.Value], markedOrder.IsMarked); for (var i = 0; i < 10; i++) { if (i != markedOrder.Value.Id) { Assert.False(results[i]); } else { Assert.True(results[i]); } } } }
public void TestAmrCasWithSameMark() { var order = new Order { Id = 1, Name = "1" }; var amr = new AtomicMarkableReference <Order>(order); Assert.Same(order, amr.Value); Assert.Equal(1, amr.Value.Id); Assert.Equal("1", amr.Value.Name); Assert.False(amr.IsMarked); var newOrder = new Order { Id = 2, Name = "2" }; Assert.True(amr.CompareExchange(order, false, newOrder, false)); Assert.Same(newOrder, amr.Value); Assert.Equal(2, amr.Value.Id); Assert.Equal("2", amr.Value.Name); }