Created
September 12, 2022 15:02
-
-
Save kant2002/06cd22eaceb4e6ba9a69c471467a5c53 to your computer and use it in GitHub Desktop.
Funny lock
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See https://aka.ms/new-console-template for more information | |
Console.WriteLine("Hello, World!"); | |
test x = new test(); | |
for(var i =0; i < 10; i++) | |
{ | |
var thread = new Thread(Worker); | |
thread.Start(); | |
} | |
for (var i = 0; i < 10; i++) | |
{ | |
var thread = new Thread(Worker2); | |
///thread.Start(); | |
} | |
void Worker() | |
{ | |
while (true) | |
{ | |
x.Test(); | |
x.Unlock(); | |
} | |
} | |
void Worker2() | |
{ | |
while (true) | |
{ | |
x.Lock(); | |
} | |
} | |
class test | |
{ | |
static readonly object myLock = new object(); | |
private int i; | |
public void Test() | |
{ | |
if (Monitor.TryEnter(myLock)) | |
return; | |
if (Monitor.IsEntered(myLock)) | |
{ | |
Console.WriteLine("WTF"); | |
Monitor.Enter(myLock); | |
} | |
} | |
public void Unlock() | |
{ | |
if (Monitor.IsEntered(myLock)) | |
{ | |
//Monitor.Pulse(myLock); | |
Monitor.Exit(myLock); | |
} | |
} | |
public void Lock() | |
{ | |
lock (myLock) | |
{ | |
i++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment