C++ Threads: try_lock_for



  • Wenn ich

    std::timed_mutex mux;
    
    void hello()
    {
        if ( mux.try_lock_for(std::chrono::seconds(10)) )
        {
            cout << "Acquired lock\n";
            mux.unlock();
        }
        else
            cout << "Timeout\n";
    
    }
    
    int main()
    {
        std::thread t1(hello), t2(hello);
        t1.join();
        t2.join();
    }
    

    ausführe bekomme ich die Ausgabe

    Acquired lock
    Timeout

    Ich würde allerdings

    Acquired lock
    Acquired lock

    erwarten.

    Compiler: g++ 4.8.1

    Irgendwo habe ich gelesen dass der g++ einen Bug drin hat oder hatte. Sieht das für euch nach einem Bug aus oder habe ich try_lock_for falsch verstanden?

    PS:
    Ich weiss dass ich den Zugriff auf std::cout auch noch synchronisieren müsste. Aber daran liegt es wohl nicht.

    *Edit
    Habe hier.. gerade folgendes gesehen:

    As with try_lock(), this function is allowed to fail spuriously and return false even if the mutex was not locked by any other thread at some point during timeout_duration.


Anmelden zum Antworten