简体   繁体   English

线程同步c#

[英]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. Monitor.EnterMonitor.Exit的调用必须由线程本身完成。 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: 要解决此问题,您需要将Enter / Exit移动到线程中,然后为监视器添加一个公共对象,如下所示:

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. 现在,当Met2进行时, t线程将无法调用Met1 ,反之亦然。

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). 此外,考虑在C#中使用lock语句,它为您包装相同的代码并处理其他陷阱(例如,例外)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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