chapter 30 - condition variables Flashcards

1
Q

What is a condition variable and what does it let a thread do?

A

A condition variable lets a thread sleep until a condition becomes true, and be woken up by another thread when the condition changes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why must a mutex be used with pthread_cond_wait()?

A

To avoid race conditions where a signal might be missed if one thread signals before another actually begins waiting

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Should you use if or while when waiting on a condition variable?

A

Use while, because the condition might have changed before the thread resumes after being signaled

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What issue can occur if both producers and consumers use the same condition variable?

A

A consumer may accidentally wake another consumer, leading to deadlock if the buffer is empty and all threads go to sleep

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How can you avoid deadlock with a single-item buffer?

A

Use two condition variables:

  • empty for producers to wait on,
  • fill for consumers to wait on,

and only signal the other type of thread

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

how is a condition variable used in pthreads?

A

It’s used in coordination with a mutex to ensure atomicity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Why must condition variables be used with a mutex?

A

Without a mutex, a race condition can occur:

  • eks:
    Parent checks done == 0 and is about to call wait()

Child sets done = 1 and calls signal() before parent calls wait()

Parent then calls wait() and sleeps forever since no one signals again
Using a mutex ensures the check and wait are atomic, avoiding lost signals

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the two cases that can happen when a parent waits for a child using condition variables?

A

Case 1:
Parent calls wait() and sleeps because done == 0
Child sets done = 1 and signals
Parent wakes and checks done == 1, proceeds

Case 2:
Child runs immediately, sets done = 1 before parent calls wait()
Parent sees done == 1 and skips waiting

How well did you know this?
1
Not at all
2
3
4
5
Perfectly