Usage of Mutex in c# - c#

I am a bit new in threading in c# and on general,
in my program I am using mutex to allow only 1 thread getting inside a critical section and for unknown reason with doing some cw prints I can see that more than 1 thread is getting inside my critical section and this is my code :
Mutex m = new Mutex();
m.WaitOne();
<C.S> // critical section here
m.ReleaseMutex();
I would very much like to know if I am doing a mistake here thanks in advance for your kind help.
EDIT:
My code include classes so it basically looks more like this:
public class test
{
private mutex m;
public test()
{
m = new mutex();
}
public func()
{
m.WaitOne();
<C.S> // critical section here
m.ReleaseMutex();
}
}

The problem here is that all your callers are using a different mutex; you need the locking object to be shared, usually by making it a field. For example, and switching to a simpler lock metaphor:
private readonly object syncLock = new object();
public void ThreadSafeMethod() {
lock(syncLock) {
/* critical code */
}
}
or using the mutex:
private readonly Mutex m = new Mutex();
public void ThreadSafeMethod() {
m.WaitOne();
try {
/* critical code */
} finally {
m.ReleaseMutex();
}
}

It looks like you give each Thread its own Mutex. That won't work.
And a Mutex is overkill in most situations. You only need:
private static object syncLock = new object(); // just 1 instance
....
lock(syncLock)
{
// critical section
}

This pattern does no locking at all. Every thread creates a new Mutex object and immediately owns the lock for it. Other threads create and use a new Mutex itself.
Consider using a regular lock()!
lock(_lockobject) {
// do inside what needs to be done - executed on a single thread only
}
where _lockobject is a simple private variable in your class:
private object _lockobject;
Edit: thanks to the commenters! Situations exist, where lock(this) can be dangerous. So I removed that.

Mutex use to identify run app instance.
using (Mutex mutex = new Mutex(true, "app name", out createdNew))
{
if (createdNew)//check app is already run
{
KillOthers();
StartApp();
}
else
{
MessageBox.Show("Another instance already running!");
}
}

May i add a correction to the accepted answer?
private readonly Mutex m = new Mutex();
public void ThreadSafeMethod() {
while(!m.WaitOne()){}
try {
/* critical code */
} finally {
m.ReleaseMutex();
}
}

Related

Avoid starting new thread with lock

Is this possible to lock method for one thread and force another to go futher rather than waiting until first thread finish? Can this problem be resolved with static thread or some proper pattern with one instance of mendtioned below service.
For presentation purposes, it can be done with static boolen like below.
public class SomeService
{
private readonly IRepository _repo;
public SomeService(IRepository repo)
{
_repo = repo;
}
private Thread threadOne;
public static bool isLocked { get; set; }
public void StartSomeMethod()
{
if(!isLocked)
{
threadOne = new Thread(SomeMethod);
isLocked = true;
}
}
public void SomeMethod()
{
while(true)
{
lots of time
}
...
isLocked = false;
}
}
I want to avoid situation when user clicked, by accident, two times to start and accidentailly second thread starts immediatelly after first finished.
You can use lock :)
object locker = new object();
void MethodToLockForAThread()
{
lock(locker)
{
//put method body here
}
}
Now the result will be that when this method is called by a thread (any thread) it puts something like flag at the beginning of lock: "STOP! You are not allowed to go any further, you must wait!" Like red light on crossroads.
When thread that called this method first, levaes the scope, then at the beginning of the scope this "red light" changes into green.
If you want to not call the method when it is already called by another thread, the only way to do this is by using bool value. For example:
object locker = new object();
bool canAccess = true;
void MethodToLockForAThread()
{
if(!canAccess)
return;
lock(locker)
{
if(!canAccess)
return;
canAccess = false;
//put method body here
canAccess = true;
}
}
Other check of canAccess in lock scope is because of what has been told on comments. No it's really thread safe. This is kind of protection that is advisible in thread safe singleton.
EDIT
After some discussion with mjwills I have to change my mind and turn more into Monitor.TryEnter. You can use it like that:
object locker = new object();
void ThreadMethod()
{
if(Monitor.TryEnter(locker, TimeSpan.FromMiliseconds(1))
{
try
{
//do the thread code
}
finally
{
Monitor.Exit(locker);
}
} else
return; //means that the lock has not been aquired
}
Now, lock could not be aquired because of some exception or because some other thread has already acuired it. In second parameter you can pass the time that a thread will wait to acquire a lock. I gave here short time because you don't want the other thread to do the job, when first is doing it.
So this solution seems the best.
When the other thread could not acquire the lock, it will go further instead of waiting (well it will wait for 1 milisecond).
Since lock is a language-specific wrapper around Monitor class, you need Monitor.TryEnter:
public class SomeService
{
private readonly object lockObject = new object();
public void StartSomeMethod()
{
if (Monitor.TryEnter(lockObject))
{
// start new thread
}
}
public void SomeMethod()
{
try
{
// ...
}
finally
{
Monitor.Exit(lockObject);
}
}
}
You can use a AutoResetEvent instead of your isLocked flag.
AutoResetEvent autoResetEvent = new AutoResetEvent(true);
public void StartSomeMethod()
{
if(autoResetEvent.WaitOne(0))
{
//start thread
}
}
public void SomeMethod()
{
try
{
//Do your work
}
finally
{
autoResetEvent.Set();
}
}

SynchronizationAttribute.SUPPORTED creates synchronization content

According to article class below is not thread safe:
I have code which gets into lock while according to my understanding has different synchronization content:
[Synchronization]
public class Deadlock : ContextBoundObject
{
public DeadLock Other;
public void Demo() { Thread.Sleep (1000); Other.Hello(); }
void Hello() { Console.WriteLine ("hello"); }
}
public class Test
{
static void Main()
{
Deadlock dead1 = new Deadlock();
Deadlock dead2 = new Deadlock();
dead1.Other = dead2;
dead2.Other = dead1;
new Thread (dead1.Demo).Start();
dead2.Demo();
}
}
It does and it is fine. But I decided to play with synchronization attributes by setting:
[Synchronization(SynchronizationAttribute.SUPPORTED)]
SUPPORTED means :
Joins the existing synchronization context if instantiated from
another synchronized object, otherwise remains unsynchronized
Since console application has no synchronization content I expect both object will have no synchronization object and should not get into deadlock. But I still have deadlock. Why?
Further have removed [Synchronization] attribute at all. Still have deadlock. What influence makes [Synchronization] attribute to object?
Here you are creating circular dependency between thread , that might lead you to stackoverflow exception , as you are not catching excpetion here you are might not able to view it. I suggest you make use of UnObservedExcpetion handler that will give you excpetion or try to handle excpetion in that same function by putting try, catch block.
To avoid this kind of situation you better make use of AutoResetEvent. below is sample code for the same.
public class MyThreadTest
{
static readonly AutoResetEvent thread1Step = new AutoResetEvent(false);
static readonly AutoResetEvent thread2Step = new AutoResetEvent(true);
void DisplayThread1()
{
while (true)
{
thread2Step.WaitOne();
Console.WriteLine("Display Thread 1");
Thread.Sleep(1000);
thread1Step.Set();
}
}
void DisplayThread2()
{
while (true)
{
thread1Step.WaitOne();
Console.WriteLine("Display Thread 2");
Thread.Sleep(1000);
thread2Step.Set();
}
}
void CreateThreads()
{
// construct two threads for our demonstration;
Thread thread1 = new Thread(new ThreadStart(DisplayThread1));
Thread thread2 = new Thread(new ThreadStart(DisplayThread2));
// start them
thread1.Start();
thread2.Start();
}
public static void Main()
{
MyThreadTest StartMultiThreads = new MyThreadTest();
StartMultiThreads.CreateThreads();
}
}

AutoresetEvent and Singleton issue

Can someone please tell me what is wrong with the following code? Ideally it should start a thread first and then wait for the set event. Instead of that it does not start the thread and just get stuck on WaitOne().
I am curious to know what happened to the thread and why?
class Program
{
static void Main(string[] args)
{
Testing t = Testing.Instance;
Console.Read();
}
}
class Testing
{
private static AutoResetEvent evt = new AutoResetEvent(false);
public static Testing Instance = new Testing();
private Testing()
{
Create();
evt.WaitOne();
Console.WriteLine("out");
}
private void Create()
{
Console.WriteLine("Starting thread");
new Thread(Print).Start();
}
private void Print()
{
Console.WriteLine("started");
evt.Set();
}
}
EDIT:
So far, the description provided by #BrokenGlass makes sense. but changing the code to the following code allows another thread can access the instance methods without constructor being completed.(Suggested by #NicoSchertler).
private static Testing _Instance;
public static Testing Instance
{
get
{
if (_Instance == null)
_Instance = new Testing();
return _Instance;
}
}
I suspect the root cause of this behavior is that the spawned thread cannot access the Print method until the constructor has finished executing - but the constructor never finishes executing because it is waiting on the signal that is triggered only from the Print method.
Replacing the evt.WaitOne() with a long Thread.Sleep() call confirms the same behavior - the constructor must finish running before any instance method of the object may execute from another thread.
The problem is that the second thread is created too early. I'm not sure why, but when started before the main program starts, it will not execute.
You should use the singleton pattern in its original version. This will work.
private static Testing _Instance;
public static Testing Instance
{
get
{
if (_Instance == null)
_Instance = new Testing();
return _Instance;
}
}
Additionally, you should not make the evt variable static. The instance variable should be the only static member of a singleton class in most cases.
My guess would be an issue with the relative timing of the static field initialization. Try initializing evt in the constructor of Testing instead:
private static AutoResetEvent evt;
public static Testing Instance = new Testing();
private Testing()
{
evt = new AutoResetEvent(false);
Create();
evt.WaitOne();
Console.WriteLine("out");
}
I should note this is really just a guess- I'd have thought this code would work fine.

How come this code does not deadlock?

Shouldn't the Log method block?
namespace Sandbox {
class Program {
static void Main(string[] args) {
var log = new Logger();
lock (log) {
log.Log("Hello World!");
}
}
}
public class Logger {
public void Log(string message) {
lock (this) {
Console.WriteLine(message);
}
}
}
}
The same thread is acquiring the same lock twice. This works because .NET supports so-called recursive locks (aka reentrant mutexes).
If a resource is locked by a thread, that thread is allowed in, even if it already owns a lock on it. The same is true for this
Object obj = new Object();
lock(obj) {
lock(obj) {
foo();
}
}
Would lock out if you couldn't get through by virtue of being the same thread.
Simple - you are running in a single thread.

C# using lock practice

I have critical section in my application which contains a lot of code:
which is better way to locking access in threadMethod:
A) lock all block:
private object locker = new object();
private void threadMethod()
{
while(true)
{
lock(locker)
{
// do work - a lot of code here
}
Thread.Sleep(2000);
}
}
B) Use additional locked access member canWork:
private static object locker = new object();
private bool canWork;
private bool CanWork
{
get { lock(locker) { return this.canWork; } }
set { lock(locker) { this.canWork = value; } }
}
private void threadMethod()
{
while(true)
{
if(CanWork)
{
// do work - a lot of code here
}
Thread.Sleep(2000);
}
}
and somewhere in code
CanWork = false;
Neither is particularly good.
The first has the disadvantage that you hold the lock for a long time.
The second has the disadvantage that the state can change after you check it.
Instead try to pass immutable arguments to your method (for example a copy of the data). You will probably still need to lock for constructing the arguments and for collecting the results but this is hopefully a much shorter period of time.
The second approach will likely lead to race conditions. Can your "a lot of code" be separated in several critical/non critical chunks?
I would use the Monitor instead. Plus do you really want while(true) because this will repeat forever?
private object syncObject = new object();
private void threadMethod()
{
bool tryToRun = true;
while(tryToRun)
{
if(Monitor.TryEnter(syncObject))
{
tryToRun = false;
// do work - a lot of code here
Monitor.Exit(syncObject);
}
else
{
Thread.Sleep(2000); // Possibly knock this up the how long you expect the lock to be held for.
}
}
}
est link:
http://msdn.microsoft.com/en-us/magazine/cc188793.aspx#fig7
Best usage is
- declare a new private sync object
- use "lock(synObject) { code here ... }

Categories