Ist die Konstruktion eines shared_ptrs aus einem weak_ptr thread safe?



  • Hallo nochmal,

    hab heute nen Lauf 😉

    Ich habe folgendes Konstrukt:

    #include <chrono>
    #include <thread>
    #include <memory>
    
    struct Data
    {
    };
    
    struct Context
    {
       std::shared_ptr<Data> Data = std::make_shared<Data>();
    };
    
    void thread_func( Data& data )
    {
       std::weak_ptr wp = data.Data;
       for( ;; )
       {
          std::shared_ptr<Data> sp = wp.lock();
          if( !sp )
          {
             break;
          }
          // do_stuff
       }
    }
    
    int main()
    {
       Context ctx;
       std::thread t( &thread_func, std::ref( ctx ) );
    
       std::this_thread::sleep_for(std::chrono::seconds( 5 ) );
       ctx.Data.reset();
    }
    

    Ist der Zugriff auf den Memory Control Block des shared_ptr threadsafe? Kann es zu race conditions bei lock() und reset() kommen oder bin ich da sicher?


Anmelden zum Antworten