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