jeudi 29 juin 2023

multithread std::shared_ptr read / write with sigsegv

a global shared_ptr g_ptr=null; then in thread 1, call init() set g_ptr=make_shared();

after that, has other thread x use write()


void write()
{
   if(g_ptr)
   {
       g_ptr->dosomething();// g_ptr.get() has a std::FILE _fd;
    }
}

then the program end. the program is

in thread 1, the global g_ptr has destory. but in other thread, func write is doing,but the _fd is set to nullptr. so the program segmentaion fault.

both init() and write() are interface, called by customer.

how can i avoid this program? use the raw pointer and provide a close() api ,may be ok. except this, how can i resolve this program with use smart pointer。 thanks.

Aucun commentaire:

Enregistrer un commentaire