stdrecursive mutex

遞迴互斥鎖允許相同的執行緒以遞迴方式鎖定資源 - 最多可達到未指定的限制。

對此,很少有真實的理由。某些複雜的實現可能需要在不釋放鎖的情況下呼叫函式的過載副本。

    std::atomic_int temp{0};
    std::recursive_mutex _mutex;
    
    //launch_deferred launches asynchronous tasks on the same thread id

    auto future1 = std::async(
                std::launch::deferred,
                [&]()
                {
                    std::cout << std::this_thread::get_id() << std::endl;

                    std::this_thread::sleep_for(std::chrono::seconds(3));
                    std::unique_lock<std::recursive_mutex> lock( _mutex);
                    temp=0;
                    
                });

    auto future2 = std::async(
                std::launch::deferred,
                [&]()
                {
                    std::cout << std::this_thread::get_id() << std::endl;
                    while ( true )
                    {
                        std::this_thread::sleep_for(std::chrono::milliseconds(1));
                        std::unique_lock<std::recursive_mutex> lock( _mutex, std::try_to_lock);
                        if ( temp < INT_MAX )
                             temp++;

                        cout << temp << endl;
                        
                    }
                });
    future1.get();
    future2.get();