Skip to content

Instantly share code, notes, and snippets.

@shirhatti
Created March 19, 2021 19:25
Show Gist options
  • Select an option

  • Save shirhatti/d98aa89aa7b93bc2e6e45942772a9ba2 to your computer and use it in GitHub Desktop.

Select an option

Save shirhatti/d98aa89aa7b93bc2e6e45942772a9ba2 to your computer and use it in GitHub Desktop.

Revisions

  1. shirhatti created this gist Mar 19, 2021.
    41 changes: 41 additions & 0 deletions Program.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    using System;
    using System.Threading;

    namespace ConsoleApp
    {
    public class Program
    {
    const int interations = 100;
    const int spinWaitIterations = 1000000;
    private static Random random = new();
    static void Main()
    {
    using var countdownEvent = new CountdownEvent(2 * interations);
    for (var i = 0; i < interations; i++)
    {
    ThreadPool.UnsafeQueueUserWorkItem(FixedDuration, countdownEvent, false);
    ThreadPool.UnsafeQueueUserWorkItem(VariableDuration, countdownEvent, false);
    }
    countdownEvent.Wait();
    }

    private static void FixedDuration(object state)
    {
    Thread.SpinWait(spinWaitIterations * 2);
    (state as CountdownEvent).Signal();
    }

    private static void VariableDuration(object state)
    {
    if (random.Next(0, 4) == 0)
    {
    Thread.SpinWait(spinWaitIterations * 5);
    }
    else
    {
    Thread.SpinWait(spinWaitIterations);
    }
    (state as CountdownEvent).Signal();
    }
    }
    }