Re: deletion of objects problem - multi-threaded program
Angus wrote:
I have written a program which runs two threads. One thread controls
the creation and modification of an object used in the program.
Another thread periodically checks a list of these objects and deletes
an object from the list if no longer required.
What indicates that the object is "no longer required"?
I have written a class to wrap the operating system specific lock /
unlock of the object. This works fine. But I get the following
problem:
1. thread 1 creates object1.
2. thread 2 checks object1 to see if ready for deletion and it
eroneously considers it is.
So, if you know that it's erroneous, why don't you simply correct the
error? What is the criterion thread 2 uses to "see if ready for
deletion"? If it's a flag, let thread 1 set it upon creation of the
object. IOW, the indicator has to be set by thread 1 and checked in
thread 2.
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.
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?
Huh?
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.
There is no need for the third thread. Define what it is that indicates
that the object is deletable, then only set that indicator in thread 1
and only check that indicator (and actually delete the object) in thread
2. Before that indicator is set, the object is alive. Setting of the
indicator and checking it should be atomic.
[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask