Tried something like this:
typedef struct __lock_t {
int flag;
} lock_t;
void init(lock_t *lock) {
lock->flag = 0;
}
void lock(lock_t *lock)
{
while (FetchAndAdd(&lock->flag) != 0)
; // spin-wait (do nothing)
}
void unlock(lock_t *lock)
{
lock->flag = 0;
}
Is this the proper way of implementing simple spin lock using fetch and add lock mechanism? If not, then what changes should be made?