Reputation:
considering following class
class test{
private: long long id;
//some field....
public: test(){};
void do_something(){
//some huge operations....
}
void do_something_else(void* arg){
//yet another huge work load.....
}
}
///////////////////////////
void* _thread(void* _ins){
test* ins=(test*)_ins;
//some work
if(<<some condition>>){delete ins;}//not thread safe, std::auto_ptr doesn't help anymore
}
///////////////////////////
int main(){
test *ins=new test();
//pass the ins to 10 thread.
}
consider there are 10 threads using a shared object, when ever one of a thread delete the object, program exit.
Questions:
how can I get any error/exception at runtime when object gets deleted? try-catch
didn't help. any solution?!
is there any thread-safe and consistence way to count the current thread using this object?
is there any event-based solution to fire an event when object is ready for purging?
thanks in advance.
Upvotes: 0
Views: 50
Reputation: 43662
C++11's shared_ptrs use atomic increments/decrements of a reference count value.
The standard guarantees only one thread will call the delete operator on a shared object.
What you need to make sure is that your critical section is synchronized, that is: the shared object isn't freed if a thread is still using it. You can use std::mutex for that (a semaphore can be implemented with a mutex and a condition variable, e.g. https://stackoverflow.com/a/4793662/1938163)
Upvotes: 1