c++实现互斥锁

typedef struct __lock_t
{
int flag;
} lock_t;

int TestAndSet(int *ptr, int new)
{
int old = *ptr;
*ptr = new;
return old;
}

void init(lock_t *mutex)
{
// 0: lock is available
// 1: lock is held
mutex->flag = 0;
}

void lock(lock_t *mutex)
{
while (mutex->flag == 1)
{ // Test the flag.
; // Wait the lock
mutex->flag = 1; // Set the lock, i.e. start to hold lock
}
}

void unlock(lock_t * mutex)
{
mutex->flag = 0;
}
posted @ 2019-07-29 23:18  柳刚  阅读(541)  评论(0编辑  收藏  举报