Hacker News new | ask | show | jobs
by dmitrygr 798 days ago
Very cool, but i imagine it'll hit a number of fun bugs randomly, with code like:

    // Reimplemented
    LONG WINAPI CORKEL32_InterlockedCompareExchange(LONG *dest,  LONG xchg,  LONG compare)
    {
      LONG temp = *dest;
    
      Trace(TRACE_FORCE_DONT_PRINT, "InterlockedCompareExchange");
    
      if (compare == *dest) {
        *dest = xchg;
      }

      return temp;
    }
Not very interlocked at all :)
2 comments

Well Windows95 probably didn't support multiple CPUs, so it's not bad :)
It did support multiple threads and pre-emptive multitasking.
Are we getting old for knowing that Reentrancy was an issue before multi-core processors became the norm for consumers?
Yup. Let’s go do some bird watching and have a beer and reminisce about computers with kilobytes of RAM, old buddy.
Yeah thanks for pointing this out. It certainly didn't _feel_ like Windows 95 supported preemption when I was using it :)
ELI5?
InterlockedCompareExchange is supposed to be an atomic compare-and-swap API. "Compare-and-swap" means the swap only occurs if the comparison succeeded, ie if the previous value of `*dest` was `compare`, then `xchg` is written to `*dest`. "Atomic" means that another thread cannot make changes between the two steps; if another thread did come in and modified the value between the comparison and the swap, the swap would not occur.

A proper implementation would use some kind of locking in the worst case, but usually would rely on hardware features to provide this atomicity. For example, on x86 this is done by the CMPXCHG family of instructions.

The mock implementation is not atomic. Another thread can change the value between the comparison and swap and the swap will still happen. As for the fix, there might be an intrinsic for it in the W95 SDK, or worst case an inline assembly implementation using CMPXCHG would do the job.