[SDL] SDL Semaphore implementation broken on Windows?
John Bartholomew
jb5950 at bristol.ac.uk
Fri Dec 28 01:00:29 PST 2007
Sam Lantinga wrote:
>> However, assuming this is the cause of my problems, there is a very
>> simple fix:
>> Windows provides InterlockedIncrement() and InterlockedDecrement()
>> functions to perform
>> increments and decrements which are guaranteed to be atomic.
>> So the fix is in thread/win32/SDL_syssem.c:
>> replace occurrences of --sem->count with InterlockedDecrement(&sem->count);
>> and replace occurrences of ++sem->count with
>> InterlockedIncrement(&sem->count);
>>
>
> I'm pretty sure the 32-bit ++ and -- operators are atomic on x86 architectures.
> Are you sure this fixes the problem?
I wouldn't bet my life on it, but I'm 99% sure. Certainly the problem
hasn't recurred at all since I made that change, and although it isn't
100% repeatable, it was happening regularly enough (say, 80 to 90% of
the times I attempted to reproduce) that I believe it would have
surfaced again if this hadn't fixed it.
Of course, it's always possible that the change just managed to push the
timings off and make it far, far rarer rather than actually eliminating
the problem.
As for ++ and -- being atomic, at the assembly code level the 'INC' and
'DEC' instructions are only atomic operations when the 'LOCK' prefix is
used (which is presumably how InterlockedIncrement/InterlockedDecrement
are implemented under the hood). I don't know whether C gives any
guarantees about their atomicity though. I don't think any compiler
would emit a lock prefix for them under all circumstances, but possibly
it does if the variable being modified is marked as volatile?
Regards,
John B
More information about the SDL
mailing list