Running method while destroying the object

前端 未结 8 1658
抹茶落季
抹茶落季 2021-01-12 22:49

A few days ago my friend told me about the situation, they had in their project. Someone decided, that it would be good to destroy the object of NotVerySafeClass

8条回答
  •  滥情空心
    2021-01-12 23:27

    (Not to promote bad design) but to answer your two questions:

    ... deny running the methods, if destructor was called already

    You can do this with the solution proposed by @snemarch and @Simon (a lock). To handle the situation where one thread is inside the destructor, while another one is waiting for the lock at the beginning of your method, you need to keep track of the state of the object in a thread-safe way in memory shared between threads. E.g. a static atomic int that is set to 0 by the destructor before releasing the lock. The method checks for the int once it acquires the lock and bails if its 0.

    ... force the destructor to wait, until any running method is over

    The solution proposed by @snemarch and @Simon (a lock) will handle this.

提交回复
热议问题