multithreading - Threadsafe test / decrement -
is code threadsafe, or fcount changed thread before interlockeddecrement executed?
procedure tmyobject.wait; begin if fcount > 0 interlockeddecrement(fcount); .. end;
it's not thread-safe.
- thread 1 reads fcount=1, evaluates condition true.
- thread 2 reads fcount=1, evaluates condition true.
- thread 1 decrements fcount 0
- thread 2 decrements fcount -1
yet assume code intended prevent reducing fcount
below zero.
you might want consider following instead:
if interlockeddecrement(fcount) < 0 interlockedincrement(fcount);
in way, 1 of 2 concurrent threads reduce value -1 , "fix mistake".
however, have side-effect fcount
may temporarily < 0
.
Comments
Post a Comment