C++ Destroy object with a mutex

79 Views Asked by At

I am making a command prompt that can create and remove (destroy) objects. You can interact with the objects via another commands and the values are sometimes exported (on request).

What if someone tries to delete object that is currently exporting or modifies any other value that's protected by a mutex? Then the mutexes are destroyed way before all operations/commands from the prompt.

How can I ensure that the object will be destroyed only after all commands that interact with it are finished? ( & when all mutexes are unlocked)

Is there any built-in functionality from std?

#include <iostream>
#include <thread>
#include <mutex>

class User
{
    private:
        int foo;
        int bar;
        
        std::mutex mu_foo;
        std::mutex mu_bar;
    public:
        User() {}
        ~User() {}
        void SetFoo(const int foo)
        {
            std::lock_guard<std::mutex> lock(mu_foo);
            this->foo = foo;
        }
        void SetBar(const int bar)
        {
            std::lock_guard<std::mutex> lock(mu_bar);
            this->bar = bar;
        }
        void Remove()
        {
            delete this;
        }
        void Export()
        {
            std::unique_lock<std::mutex> lock_foo(mu_foo);
            // export foo
            lock_foo.unlock();
            /*
                more exporting
            */
            std::unique_lock<std::mutex> lock_bar(mu_bar);
            // export foo
            lock_bar.unlock();
            /*
                more exporting
            */
        }
};

int main()
{
    User* user = new User();
    
    // simulate 2 commands from different clients
    //  if export was first - export and remove
    //  if remove was first - remove and dont allow to export
    
    std::thread t1([&user](){
        user->Export();
    });
    
    std::thread t2([&user](){
        user->Remove();
    });
    
    t1.join();
    t2.join();

    return 0;
}
0

There are 0 best solutions below