[openbeos-midi] Re: BMidiEndPoint

  • From: Michael Pfeiffer <michael.pfeiffer@xxxxxxxxx>
  • To: openbeos-midi@xxxxxxxxxxxxx
  • Date: Fri, 11 Oct 2002 08:59:55 -0700

>I still think it is not thread save. can you please prove why do you think it 
>should be save=3F
>The comment says:
>// thread-safe as long as thread that calls acquire has already a reference to 
>the object

>If you have only one single thread that is calling aquire or release, you 
>don't need atomic=5Fadd() at all.
>Assuming one thread calls Acquire(), and passes the pointer to another thread, 
>which calles release.
>If you have two or more threads, the following can happen:
>fRefCount is 1
>Thread 1 calls Acquire, fRefCount is now 2
>Thread 2 calls Release, and gets interrupted after atomic=5Fadd, but before 
>if(), fRefCount is now 1
>Thread 1 calls Release, (does not get interrupted) fRefCount is now 0, and 
>executes "delete this";
>Thread 2 continues, checks fRefCount, it is still 0, and executes "delete 
>You see, it is NOT multi thread save. You delete this twice.
>You should really use the return value of atomic=5Fadd() to avoid that.

You are right, how could I overlook this. Promise to examine my own code the 
next time
before replying :)

I assume that Thread 2 is started after Thread 1 has called Acquire.

Otherwise there would be this problem:
Assume the same situation as above: fRefCount is 1
Thread 1 calls Acquire, and gets interrupted at the begin of the method body, 
fRefCount is not changed yet
Thread 2 calls Release, decrements fRefCount to 0 and deletes the object
Thread 1 continues accessing data of a not existing object! Thread 1 has no 
chance to detect that
the object is deleted.

- Michael

Other related posts: