0

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.

  • 1
    You can use C++11 shared pointers (they have a reference count for shared instances): http://en.cppreference.com/w/cpp/memory/shared_ptr Be sure to synchronize the check for that count in your threads (e.g. use a mutex or something similar) – Marco A. Feb 12 '14 at 17:12
  • Unrelated to your problem, but don't have global names with leading underscores, as those are reserved by the specification. – Some programmer dude Feb 12 '14 at 17:14
  • @DavidKernin thanks dude, either `std::shared_ptr` doesn't help. because as you mentioned I have to count the thread safe. but this is not safe at all. because two threads would change the value at a time(one increase/one decrease), and if first one goes first, it will delete the object which causes error for second thread. –  Feb 12 '14 at 17:16
  • Use std::shared_ptr, which is thread safe. In general, you'll want to have critical sections in your multi-threaded code to protect shared objects. Look up std::mutex. – segfault Feb 12 '14 at 17:16
  • shared_ptr + mutex is the way to go then, read again my post – Marco A. Feb 12 '14 at 17:16

1 Answers1

1

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)

Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246