简体   繁体   中英

thread synchronization c#

I have a multi threaded application.

I am trying to synchronize / thread-safe it

static void Main(string[] args)
{
   Thread t = new Thread(()=>Met1(x));
   Monitor.Enter(t);
   t.start();
   Monitor.Exit(t);

   Thread t2 = new Thread(()=>Met2(x,y));
   Monitor.Enter(t2);
   t2.start();
   Monitor.Exit(t2);
}

However, the application is not thread-safe / synchronized.

The call of Monitor.Enter and Monitor.Exit must be done by thread themselves. In your code, this is done by the main thread in the process of setting up the two threads. Moreover, that needs to be a monitor of the same object, not two different objects like it is in your case.

To fix this, you need to move the Enter / Exit onto the thread into the delegate, and add a common object for the monitor, like this:

object mon = new object();
Thread t = new Thread(()=>{
    Monitor.Enter(mon);
    Met1(x);
    Monitor.Exit(mon);
});
Thread t2 = new Thread(()=>{
    Monitor.Enter(mon);
    Met2(x,y);
    Monitor.Exit(mon);
});
t.start();
t2.start();

Now the t thread would not be able to call Met1 while Met2 is going, and vice versa.

You are using two different monitors. If you want synchronization, use the same monitor. I also suggest using monitors on objects other than the threads (for example a new object by itself as a lock). Further, consider using the lock statement in C# which wraps the same code for you and takes care of other gotchas as well (exceptions for example).

object synchronizationLock = new object();
lock (synchronizationLock)
{
    // Place logic here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM