Read OSPP §5, Synchronizing Access to Shared Objects.
Exercise: memory models due next Monday morning & lab 4 out
put(), get()
put()stable[0]->next - one winner, others lose-fsanitize=thread to gcc/clang compile optionsput()
atomic_fetch_add and atomic_load
done += 1; while (done < nthread); work?gcc -O2: infinite loop - why?get(), or del()?acquire(l); x = x + 1; release(l);put(a + 100) and put(b - 100) must be both effective, or neitherstruct lock { int locked; };
void acquire(struct lock *l)
{
for (;;) {
if (l->locked == 0) { // A: test
l->locked = 1; // B: set
return;
}
}
}
void release(struct lock *l)
{
l->locked = 0;
}ph.c: what can go wrongstruct lock { _Atomic int locked; };
void acquire(struct lock *l)
{
for (;;) {
if (atomic_exchange(&l->locked, 1) == 0)
return;
}
}xchg instruction
l->locked was 1, set it to 1 again & return 1l->locked was 0, at most one xchg would see & return 0xchg is implementedspinlock.c