
typedef volatile int lock_t[1];

inline void LockInit(lock_t hPtr)  { *hPtr = 0; }

inline void Lock(lock_t hPtr)
{
#ifdef WIN64_LOCK_INTERLOCK  // Win64にはインラインアセンブラがない
  for (;;) {
    if ( _interlockedbittestandset((long*)hPtr, 0)==0 ) return;
    while (*hPtr);
  }
#else

#if defined(_MSC_VER) // Visual C++
  __asm
    {
      mov     ecx, hPtr
 la:  mov     eax, 1
      xchg    eax, [ecx]
      test    eax, eax
      jz      end
 lb:
      pause    // Hyper-Threadingで効果的
      mov     eax, [ecx]
      test    eax, eax
      jz      la
      jmp     lb
 end:
    }
#else // Linux, gcc
  int itemp;
  for (;;) {
    asm ( "1:   movl     $1,  %1 \n\t"
          "     xchgl   (%0), %1 \n\t"
        : "=g" (hPtr), "=r" (itemp) : "0" (hPtr) );
    if ( ! itemp ) { return; }
    while ( *hPtr );
  }
#endif

#endif
}

inline void UnLock(lock_t hPtr) { *hPtr = 0; }
