CS 61 Makeup Test
1. Racing form (9 points)
Every question in this section uses these global variables:
int n = 1;
int x = 100;
std::atomic<int> a = 1;
std::mutex m;
In each question, the main thread starts two concurrent threads, T1 and T2, then joins them. Mark whether the corresponding code has a data race, and if it does not, list all possible final values of the named variable. (Each question starts fresh from the initial values above.)
QUESTION 1A.
-
// Thread T1 ++n; -
// Thread T2 ++n;
- Data race
- No data race; all possible final values of
n:
QUESTION 1B.
-
// Thread T1 ++n; -
// Thread T2 ++x;
- Data race
- No data race; all possible final values of
n:
QUESTION 1C.
-
// Thread T1 ++a; -
// Thread T2 ++a;
- Data race
- No data race; all possible final values of
a:
QUESTION 1D.
-
// Thread T1 a = a + 1; -
// Thread T2 a = a * 2;
- Data race
- No data race; all possible final values of
a:
QUESTION 1E.
-
// Thread T1 m.lock(); n = n + 1; m.unlock(); -
// Thread T2 m.lock(); n = n * 2; m.unlock();
- Data race
- No data race; all possible final values of
n:
QUESTION 1F.
-
// Thread T1 m.lock(); ++n; m.unlock(); -
// Thread T2 if (n == 1) { m.lock(); ++n; m.unlock(); }
- Data race
- No data race; all possible final values of
n:
QUESTION 1G.
-
// Thread T1 a.exchange(5); -
// Thread T2 if (a.exchange(7) == 1) { ++a; }
Reminder: a.exchange(v) sets a to v and returns the previous value
of a, all in one atomic step.
- Data race
- No data race; all possible final values of
a:
2. Cyberlocks (15 points)
You’re at an internship at a famous company, FaceXSINeuraBoring, helping to
develop a new operating system for cyberintelligent systems. This OS has
atomics and std::condition_variable_any, but no std::mutex. You decide to
build your own mutex. You start with a spinlock:
struct spinlock61 {
std::atomic<int> v = 0; // 0 means unlocked, 1 means locked
void lock() {
while (v.exchange(1) == 1) { /* do nothing */ }
}
void unlock() {
v = 0;
}
};
A spinlock provides mutual exclusion, but a thread waiting for it polls. You want a mutex whose waiting threads block. Here’s your design; three pieces are missing.
struct mutex61 {
spinlock61 s;
bool locked = false; // true iff some thread holds the mutex
std::condition_variable_any cv;
void lock() {
s.lock();
while (____(a)____) {
____(b)____;
}
locked = true;
s.unlock();
}
void unlock() {
s.lock();
locked = false;
____(c)____;
s.unlock();
}
};
Reminders: v.exchange(x) sets v to x and returns the previous value of
v, all in one atomic step. And cv.wait(lk) works with any object lk that
has lock() and unlock() functions, including a spinlock61: it atomically
calls lk.unlock() and blocks, and calls lk.lock() again before returning.
QUESTION 2A. Fill in the three blanks.
- (a)
- (b)
- (c)
QUESTION 2B. Which of these statements about the completed mutex61
are true? Select all that apply.
- The spinlock
sis never locked while the mutex is locked. - A thread that holds the mutex (it has returned from
mutex61::lock()and has not yet calledmutex61::unlock()) also holds the spinlocks. - A thread that is blocked in
cv.wait(s)does not hold the spinlocks. - A thread calling
mutex61::lock()might poll, but only while some other thread is executing the few instructions betweens.lock()ands.unlock()in one ofmutex61’s functions. cv.wait(s)changes the spinlock so thats.lock()blocks instead of polling.- None of the above
QUESTION 2C. Your boss, Smelin Husk, now tells you to get rid of
std::condition_variable_any too. You must replace it with your own class,
cv61, built from two new system calls that Smelin has added to the kernel:
pb_block()blocks the calling thread until some other thread callspb_unblock().pb_unblock()wakes up every thread that is currently blocked inpb_block(). If no thread is blocked, it does nothing.
Here’s your first attempt. You change mutex61 to use it (so its cv member
has type cv61), and make no other changes.
struct cv61 {
void wait(spinlock61& lk) {
lk.unlock();
pb_block();
lk.lock();
}
void notify_all() {
pb_unblock();
}
};
Thread T1 holds a mutex61, and thread T2 calls mutex61::lock() on the same
mutex. Put the following four events in an order that leaves T2 blocked
forever, even though the mutex ends up unlocked and no other thread ever uses
it.
- T2, in
cv61::wait, executeslk.unlock()(line 3). - T2, in
cv61::wait, callspb_block()(line 4). - T1, in
mutex61::unlock, lockssand setslocked = false. - T1, in
cv61::notify_all, callspb_unblock()(line 8).
Order:
QUESTION 2D. How would you describe this bug? Select all that apply.
- Data race
- Race condition
- Sleep–wakeup race
- Lost wakeup
- Deadlock
- Undefined behavior
- None of the above
QUESTION 2E. You eventually convince Smelin that a correct condition
variable is impossible with his interface as it is, and he offers you a choice
of four new interfaces. Choose one and use it to write a correct cv61. You
may add members to cv61, and you may use spinlock61, atomics, and standard
containers such as std::vector.
- Clear and block. In one atomic step,
pb_block(std::atomic<int>* x)both sets*x = 0and blocks the calling thread.pb_unblock()is unchanged: it wakes up every thread currently blocked inpb_block. - Persistent wakeups.
int pb_gettid()returns the calling thread’s ID.pb_block()blocks the calling thread.pb_unblock(int tid)wakes up threadtidif it is blocked inpb_block; if threadtidis not blocked, then its next call topb_block()returns immediately instead of blocking. - Numbered wakeups.
pb_block(int n)blocks the calling thread.pb_unblock(int n)wakes up every thread currently blocked in a call topb_blockwith the same argumentn; threads blocked with a different argument stay blocked. If no thread is blocked with argumentn, it does nothing. - Block if unchanged.
pb_block(std::atomic<int>* x, int expected)performs the following in one atomic step: if*x == expected, it blocks the calling thread; otherwise it returns immediately.pb_unblock()is unchanged: it wakes up every thread currently blocked inpb_block.
Note: When a system call performs several actions “in one atomic step,” nothing any other thread does can happen between those actions. Every other thread’s operations, including its system calls, take effect either entirely before the step or entirely after it.
Write your cv61 here, including any members you add and both wait(spinlock61& lk) and notify_all(). You may assume that every caller of wait calls it
in a loop that rechecks its condition.
3. Single slot silliness (16 points)
Here is a correct, simple implementation of part of the IO61 library from problem set 5. It uses a single-slot cache with the representation from section.
struct io61_file {
int fd;
int mode; // O_RDONLY or O_WRONLY
static constexpr off_t bufsize = 4096;
unsigned char cbuf[bufsize];
off_t tag = 0; // file offset of first byte in `cbuf`
off_t pos_tag = 0; // file offset of next byte to read or write
off_t end_tag = 0; // file offset 1 past last valid `cbuf` byte
};
void io61_fill(io61_file* f) { // read caches only
f->tag = f->pos_tag = f->end_tag;
ssize_t n = read(f->fd, f->cbuf, f->bufsize);
if (n > 0) {
f->end_tag = f->tag + n;
}
}
int io61_readc(io61_file* f) {
if (f->pos_tag == f->end_tag) {
io61_fill(f);
if (f->pos_tag == f->end_tag) {
return -1; // end of file
}
}
unsigned char ch = f->cbuf[f->pos_tag - f->tag];
++f->pos_tag;
return ch;
}
void io61_flush(io61_file* f) { // write caches only
ssize_t n = write(f->fd, f->cbuf, f->end_tag - f->tag);
assert(n == f->end_tag - f->tag);
f->tag = f->end_tag;
}
int io61_writec(io61_file* f, int c) {
if (f->end_tag == f->tag + f->bufsize) {
io61_flush(f);
}
f->cbuf[f->end_tag - f->tag] = c;
++f->pos_tag;
++f->end_tag;
return 0;
}
int io61_seek(io61_file* f, off_t off) {
if (f->mode == O_WRONLY) {
io61_flush(f);
}
if (lseek(f->fd, off, SEEK_SET) == -1) {
return -1;
}
f->tag = f->pos_tag = f->end_tag = off;
return 0;
}
int io61_close(io61_file* f) {
if (f->mode == O_WRONLY) {
io61_flush(f);
}
int r = close(f->fd);
delete f;
return r;
}
QUESTION 3A. Recall that the cat61 and reverse61 test programs each
read a single input file and generate a single output file, reading and
writing a character at a time using io61_readc and io61_writec. However,
reverse61 reads the input file backwards by calling io61_seek before
each character. (cat61 never calls io61_seek.)
The code above produces correct answers for reverse61 tests, but runs much
slower than stdio. Why? Explain briefly.
QUESTION 3B. You need to grade six students’ turnins for this problem set. Their code is the same as the correct version above, except that each of them made one change. Match each student’s change to the behavior it causes. Write one behavior number per student; a behavior may be used more than once or not at all.
-
Students
-
Alireza deletes line 34.
-
Barnaby changes
unsigned chartocharon line 26. -
Charli deletes lines 51–53.
-
Dwarkesh changes
f->bufsizeto8on line 13. -
Enxi changes
f->end_tagtof->pos_tagon line 34. -
Feifei deletes line 15.
-
-
Behaviors
- The output of
cat61is often missing bytes at the end. cat61often encounters an out-of-bounds memory access (a sanitizer error or crash).cat61stops copying early, but only for input files that contain certain byte values.cat61works, butreverse61writes the wrong bytes.cat61produces correct output, but makes far more system calls than the original.cat61never terminates.- No change: the student’s code is also correct and just as fast.
- The output of
Reminder: The detachable reference page at the end of the exam has a full copy of the
io61code for your reference.
- Alireza:
- Barnaby:
- Charli:
- Dwarkesh:
- Enxi:
- Feifei:
QUESTION 3C. Another student, Greg, deletes lines 59–61, so that
io61_close never calls io61_flush, and then runs cat61 on an input file
whose size is 40,980 = 10 × 4096 + 20 bytes. What is
the size of the resulting output file? (You may write your answer as an
expression, such as “10 × 4096 + 20”.)
4. Reference check (20 points)
This question concerns the following reference string, which contains ten accesses to five different blocks.
1 2 3 1 5 2 1 4 2 4
All caches in this question are fully associative and start out empty.
QUESTION 4A. Complete this diagram to show how a three-slot LRU cache processes the reference string. As in lecture, each column shows the cache’s contents after the corresponding access. Circle each block when it is loaded into the cache (a miss).
| Refstr→ | 1 | 2 | 3 | 1 | 5 | 2 | 1 | 4 | 2 | 4 |
|---|---|---|---|---|---|---|---|---|---|---|
| Slot A | ① | 1 | 1 | |||||||
| B | ② | 2 | ||||||||
| C | ③ |
QUESTION 4B. How many hits does the three-slot LRU cache observe?
Hits:
QUESTION 4C. How many hits does a three-slot FIFO cache observe on this reference string? (You may use the diagram for scratch work, but only your number will be graded.)
| Refstr→ | 1 | 2 | 3 | 1 | 5 | 2 | 1 | 4 | 2 | 4 |
|---|---|---|---|---|---|---|---|---|---|---|
| Slot A | ||||||||||
| B | ||||||||||
| C |
Hits:
QUESTION 4D. Which of these statements are true for every reference string? Select all that apply.
- A four-slot FIFO cache observes at least as many hits as a three-slot FIFO cache.
- A four-slot LRU cache observes at least as many hits as a three-slot LRU cache.
- A three-slot cache using Bélády’s optimal algorithm observes at least as many hits as a three-slot LRU cache.
- A three-slot LRU cache observes at least as many hits as a three-slot FIFO cache.
- None of the above
QUESTION 4E. The remaining questions concern implementations of a 3-slot, fully-associative cache. Here’s a sketch of the implementation framework:
struct slot {
int address; // address of this block (e.g., 1–5); 0 = empty
unsigned long info; // used to choose a slot to evict
void load(); // called after a miss that used this slot
void hit(); // called after a hit that used this slot
};
slot cache[3];
unsigned long now = 1; // current time; incremented by 1 on each step
Does struct slot contain any padding, and if so, where?
QUESTION 4F. Assuming cache is located at address 0x601040, compute
the following numeric values. You may use hexadecimal.
sizeof(cache):(uintptr_t) &cache[2].info:
QUESTION 4G. Write the bodies of slot::load() and slot::hit() so that
the cache implements the FIFO eviction policy. Your code may use now; if
a body should be empty, write “empty”. Note that when the cache needs to evict
a block, it always evicts the slot with the smallest info.
-
void slot::load() { -
void slot::hit() {
QUESTION 4H. The cache you implemented in the previous question starts out
empty, with now == 1, and then processes a reference string. Each access is
one step. Afterward, a debugger shows these bytes of memory starting at the
address of cache. (Each row shows 16 bytes in increasing address order.)
0x601040: 04 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00
0x601050: 05 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00
0x601060: 01 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00
0x601070: 02 FF FF FF BA BA BA BA BA BA BA BA 00 00 00 00
Finish the following reference string so that processing your reference string could have created this dump.
Reference string: 2 3 1
QUESTION 4I. Here are three versions of slot::hit(), compiled to x86-64
assembly. (Recall that a member function’s this pointer is passed like a
first argument.) One implements LRU, one implements FIFO, and one implements
LFU (least frequently used), in which the block evicted is the one that
has been accessed the fewest number of times. Which is which?
-
X: addq $1, 8(%rdi) ret -
Y: ret -
Z: movq now(%rip), %rax movq %rax, 8(%rdi) ret
- LRU:
- FIFO:
- LFU:
QUESTION 4J. When the cache needs to evict a slot, it calls a function
victim whose arguments and return type you don’t know. Here is its assembly.
victim:
movslq %esi, %rsi
movq %rdi, %rax
movq %rdi, %rdx
salq $4, %rsi
addq %rdi, %rsi
.L2:
cmpq %rsi, %rdx
je .L4
movq 8(%rax), %rcx
cmpq %rcx, 8(%rdx)
jnb .L3
movq %rdx, %rax
.L3:
addq $16, %rdx
jmp .L2
.L4:
ret
Which of these statements are true based on this assembly? Select all that apply.
- This function accepts at least two arguments.
- This function’s first argument is a pointer.
- This function’s second argument is a pointer.
- This function returns a pointer.
- This function contains a loop.
- This function can modify memory.
- This function calls another function.
- None of the above