簡體   English   中英

無法同步兩個線程

[英]unable to synchronize two threads

如果我做:

ConsoleApp1:

    bool mutexCreated;
    var mutex = new Mutex(true, "MemoryMappedFileMutex", out mutexCreated);

    Console.Write("Run Console App2 then press enter");
    Console.Read();

    // do work
    Thread.Sleep(5000);

    mutex.ReleaseMutex(); // makes console app 2 to stop waiting

ConsoleApp2

    var mutex = Mutex.OpenExisting("MemoryMappedFileMutex");

    mutex.WaitOne();

    // continue executing once console app 1 releases mutex

一切都很好。 我必須首先啟動consoleApp1才能使用此算法。

現在我的問題是我希望consoleApp2充當服務器。 因此,我想首先啟動該應用程序。 問題是,如果我這樣做:

    bool mutexCreated;
    var mutex = new Mutex(true, "MemoryMappedFileMutex", out mutexCreated);

    mutex.WaitOne();  // <------ mutex will not wait why????

如果我做mutex.WaitOne()該線程不會等待。 換句話說,我想首先啟動consoleApp2並讓該應用程序等到我在控制台應用程序1上以某種方式發出互斥鎖信號....

在您的服務器應用程序中,嘗試使用false作為第一個參數調用構造函數,以便調用線程最初不會擁有該互斥鎖。

從擁有線程等待Mutex不會阻塞,並且您指定true為第一個Mutex構造函數arg,這表示它已創建已由當前線程擁有。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM