Hi,
Angus wrote:
1. thread 1 creates object1.
2. thread 2 checks object1 to see if ready for deletion and it
eroneously considers it is.
why? Thread 2 must not do this mistake.
3. thread 1 modifies object1.
4. (simultaneously with 3.) deletes object1.
Result is an access violation as at 3. a pointer to object1 is
dereferenced.
Obviously.
My possible solutions for this problem are:
1. Add a lock and unlock function to the object1 class. Then have to
lock, perform manipulation, then unlock. But then if a instruction
was waiting for the access control/critical section to free up and the
object gets deleted - then what happens?
A lock won't solve your problem. (It might solve other concurrency issues.)
2. Don't actually delete object1. Simply mark it as deletable. then
have another thread check when possible to delete object1 say every
hour - when there is no chance that thread1 would be doing anything
with object1.
The expression 'no chance' has no meaning for concurrency issues. So
don't rely on that. Although think what happens if all objects that your
application uses reside in memory for at least one hour. Depending on
you application this might be a serious problem.
Noe of these solutions seems ideal.
True. You need thread 1 to tell when it does no longer need the object.
The easiest solution is to use reference counting. And the strongly
recommended way to do so is to use smart pointers. Have a look at
boost::shared_ptr or boost::intrusive_ptr. Once you use them
consequently you might not need thread 2 at all, because it is straight
forward when the object is no longer needed. This is exactly when no
(smart) pointer to the object exists. In this case you cannot access the
object anymore because you don't know where it lies in memory.
The smart pointer will automatically delete your object if the last
reference has gone. For this to work, you must not hold any ordinary
pointers or references to object. Exception: if you are absolutely sure
that a longer lived smart pointer instance points to the same object the
whole time.
Agree, reference counting solve this issue easily.
heard about smart-pointers or reference counting. They had exactly the
orderly. They came up with a reaper thread whose sole purpose was to
destroy objects. And it worked about 99% of the time, since with no
the application or make it use corrupted objects.