2

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?

Kara
  • 6,115
  • 16
  • 50
  • 57
  • Which architecture? Which language? – curiousguy Dec 05 '19 at 16:26
  • operating system. C language –  Dec 11 '19 at 03:33
  • Which CPU? Intel? – curiousguy Dec 11 '19 at 03:48
  • 1
    For "C abstract machine"; I think `lock->flag` needs to be volatile and/or atomic (otherwise there's no guarantee that other CPUs/threads will be able to see that `lock->flag = 0;` occurred); but otherwise it looks correct. I don't know if "merely correct" is considered "the proper way" (for my personal opinion, "the proper way" excludes artificial restrictions like "must use FetchAndAdd"). – Brendan Dec 11 '19 at 04:10

0 Answers0