Skip to content

Instantly share code, notes, and snippets.

@MeinLiX
Last active June 7, 2021 10:28
Show Gist options
  • Save MeinLiX/cc9bd43824641c6159d3543d9c172f35 to your computer and use it in GitHub Desktop.
Save MeinLiX/cc9bd43824641c6159d3543d9c172f35 to your computer and use it in GitHub Desktop.
Mutex test c#
using System;
using System.Diagnostics;
using System.Threading;
namespace Project
{
class Program
{
private static readonly Mutex m = new ();
private const int N = 1000;
private static int x = 0;
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
#region noMutex
sw.Start();
Thread incrTh = new (Incr);
Thread decrTh = new (Decr);
incrTh.Start();
decrTh.Start();
sw.Stop();
Console.WriteLine($"NoMutex: {sw.ElapsedMilliseconds} (ms) | {sw.ElapsedTicks} (ticks)\n");
sw.Reset();
#endregion
#region OurMutex
sw.Start();
Thread OurincrTh = new(OurIncr);
Thread OurdecrTh = new(OurDecr);
OurincrTh.Start();
OurdecrTh.Start();
sw.Stop();
Console.WriteLine($"OurMutex: {sw.ElapsedMilliseconds} (ms) | {sw.ElapsedTicks} (ticks)\n");
sw.Reset();
#endregion
#region EveryMutex
sw.Start();
Thread EveryincrTh = new(EveryIncr);
Thread EverydecrTh = new(EveryDecr);
EveryincrTh.Start();
EverydecrTh.Start();
sw.Stop();
Console.WriteLine($"EveryMutex: {sw.ElapsedMilliseconds} (ms) | {sw.ElapsedTicks} (ticks)\n");
sw.Reset();
#endregion
}
#region noMutex Fn
private static void Incr()
{
for (int i = 0; i < N; i++)
x++;
}
private static void Decr()
{
for (int i = N; i > 0; i--)
x--;
}
#endregion
#region OurMutex Fn
public static void OurIncr()
{
m.WaitOne();
for (int i = 1; i < N; i++)
x++;
m.ReleaseMutex();
}
public static void OurDecr()
{
m.WaitOne();
for (int i = N; i > 0; i--)
x--;
m.ReleaseMutex();
}
#endregion
#region EveryMutex Fn
public static void EveryIncr()
{
for (int i = 1; i < N; i++)
{
m.WaitOne();
x++;
m.ReleaseMutex();
}
}
public static void EveryDecr()
{
for (int i = N; i > 0; i--)
{
m.WaitOne();
x--;
m.ReleaseMutex();
}
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment