- 论坛徽章:
- 0
|
OK. 如果你们有Linux/i386, 试一试这个程序. 我们再接着讨论.
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- long
- __attribute__ ((__unused__))
- InterlockedExchange(long* ipLong, long iNewVal)
- {
- register long __result;
- __asm__ __volatile__ ("lock; xchgl %0,%2"
- : "=r" (__result)
- : "0" (iNewVal), "m" (*ipLong)
- : "memory");
- return __result;
- }
- typedef long spinlock_t;
- #define MAX_SPIN 500
- #define UNLOCKED 1
- #define LOCKED 0
- class SpinLock
- {
- public:
- SpinLock() { mLock=UNLOCKED; }
- ~SpinLock() {}
- void Lock();
- void Unlock() { InterlockedExchange(&mLock, UNLOCKED); }
- private:
- spinlock_t mLock;
- };
- void SpinLock::Lock()
- {
- while (1)
- {
- for(int count=0; count<MAX_SPIN; count++)
- {
- if(InterlockedExchange(&mLock, LOCKED) != LOCKED)
- return;
- }
- ::sched_yield();
- }
- }
- int main()
- {
- int rc=0;
- SpinLock aLock;
- // Get lock
- aLock.Lock();
- // Release lock
- aLock.Unlock();
- // dead lock
- aLock.Lock();
- aLock.Lock();
-
- /**********************************************************************
- ** I will never get this far.
- **********************************************************************/
- return rc;
- }
- > g++ -m32 foo.cpp
- > a.out
复制代码 |
|