3

マルチスレッドアプリケーションがあります。

同期/スレッドセーフにしようとしています

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);
}

ただし、アプリケーションはスレッドセーフ/同期化されていません。

4

2 に答える 2

3

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.

于 2013-04-15T01:25:15.750 に答える
1

2 つの異なるモニターを使用しています。同期が必要な場合は、同じモニターを使用してください。また、スレッド以外のオブジェクトでモニターを使用することもお勧めします (たとえば、新しいオブジェクト自体をロックとして使用するなど)。さらに、C# で lock ステートメントを使用することを検討してください。これは、同じコードをラップし、他の落とし穴 (例外など) も処理します。

object synchronizationLock = new object();
lock (synchronizationLock)
{
    // Place logic here
}
于 2013-04-15T01:26:46.857 に答える