Activity 1
In this activity, you will implement a mutex object with correct behaviors by modifying the following code.
// unlocked: state = 0;
// locked: state = 1;
struct mutex {
std::atomic<int> state = 0;
void lock() {
// Your code should have the same effect as this code,
// but it must behave as if it executes in one atomic step—
// even if multiple threads are simultaneously calling
// lock() and unlock() on the same mutex.
// while (this->state == 1) {
// }
// this->state = 1;
}
void unlock() {
// Same note as above.
// this->state = 0;
}
}
The atomic state
object supports reads and writes, but you can also use
atomic read-modify-write arithmetic primitives. For instance, these operations
modify state
in an atomic way:
++state; // atomic increment
--state; // atomic decrement
Activity 2
Now let's try a different way of implementing mutex with just a single bit (spinlock). We add a new primitive:
// Atomically swap the value of `*this` with `value`.
// Returns the previous value of `*this`.
int std::atomic<int>::swap(int value);
struct mutex {
std::atomic<int> state = 0;
void lock () {
// while (this->state == 1) {
// }
// this->state = 1;
}
void unlock() {
// this->state = 0;
}
}