30. Condition variables Flashcards

1
Q

What is condition variable?

A

It’s an explicit queue that threads can put themselves on when some state of execution (some condition) is not as desired. Some other thread, when it changes said state, can then wake those waiting thread(-s) by signaling.

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

Definition of condition variable

A

pthread cond_t c = null;

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

Provide interfaces for wait() and signal() calls for threads

A

pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m);

pthread_cond_signal(pthread_cond_t *c);

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

What’s responsibility of wait() call?

A

The wait() call assumes that the passed lock is already held when it’s called. It’s responsibility is to release the lock and put the calling thread to sleep (atomically). When the thread wakes up after signal, it must re-acquire the lock before returning to the caller.

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

Why are locks around changing the state variable, signaling, waiting are important?

A

To avoid race condition since the state of condition variable also changes. And to avoid forever sleeping threads

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

What’s responsibility of signal() call?

A

To wake up a thread from a queue (condition variable) and let it recheck its condition and decide whether it can execute further or go back to sleep

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

What issue can arise when consumer/producer threads use the same single condition variable? Considering we can’t do a broadcast call

A

They might all go to sleep because wrong thread (i.e consumer-consumer or producer-producer) is woken up

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

Why should we use while and not if while checking the condition variable?

A

Because another thread might sneak in after the original thread was woken up. In this case, the sneaky thread will consume a value from some buffer and the original thread will continue its execution without recheck failing because buffer is now empty

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

How is an issue of wakening up a wrong thread in memory allocation library is solved?

A

With broadcast signaling pthread_cond_broadcast().

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