...

/

A Failed Attempt: Just Using Loads/Stores

A Failed Attempt: Just Using Loads/Stores

This lesson discusses how the use of loads and stores to implement locks, falls short.

We'll cover the following...

To move beyond interrupt-based techniques, we will have to rely on CPU hardware and the instructions it provides us to build a proper lock. Let’s first try to build a simple lock by using a single flag variable. In this failed attempt, you’ll see some of the basic ideas needed to build a lock, and (hopefully) see why just using a single variable and accessing it via normal loads and stores is insufficient.

Press + to interact
typedef struct __lock_t { int flag; } lock_t;
void init(lock_t *mutex) {
// 0 -> lock is available, 1 -> held
mutex->flag = 0;
}
void lock(lock_t *mutex) {
while (mutex->flag == 1) // TEST the flag
; // spin-wait (do nothing)
mutex->flag = 1; // now SET it!
}
void unlock(lock_t *mutex) {
mutex->flag = 0;
}

In this first attempt (in the code widget above), the idea is quite simple: use a simple variable (flag) to ...