Untitled

mail@pastecode.io avatar
unknown
csharp
6 months ago
1.6 kB
2
Indexable
Never
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"}");
                    else
                        Console.WriteLine("Ништяк, браток!");
                }
            }
            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();
Leave a Comment