Untitled
unknown
csharp
2 years ago
1.5 kB
6
Indexable
var threads = new List<Thread>(); var ct = new CancellationTokenSource(); var writerCount = 8; var readerCount = 16; var dictionaryCount = 100; var dictionary = Enumerable.Range(0, dictionaryCount).ToDictionary(x => x.ToString(), x => x.ToString()); for (var i = 0; i < writerCount; i++) { var thread = new Thread(() => { while (!ct.IsCancellationRequested) { var index = GenIndex(); lock (dictionary) dictionary[index] = index; Thread.Sleep(5); lock (dictionary) dictionary.Remove(GenIndex()); } }); threads.Add(thread); } for (var i = 0; i < readerCount; i++) { var thread = new Thread(() => { while (!ct.IsCancellationRequested) { var index = GenIndex(); try { if (dictionary.TryGetValue(index, out var outIndex)) { if (outIndex != index) Console.WriteLine($"error: expected {index}, but found {outIndex ?? "null"}"); } } catch (Exception e) { Console.WriteLine(e.Message); } } }); threads.Add(thread); } threads.ForEach(t => t.Start()); Console.WriteLine("run"); Console.ReadKey(); ct.Cancel(); threads.ForEach(t => t.Join()); string GenIndex() => Random.Shared.Next(dictionaryCount).ToString();
Editor is loading...
Leave a Comment