Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Correcting links;NFC

Both thread safety and liveness are concerns when using condition variables. The thread-safety property requires that all objects maintain consistent states in a multithreaded environment [Lea 2000]. The liveness property requires that every operation or function invocation execute to completion without interruption; for example, there is no deadlock.

Condition variables must be used inside a while loop (see CON54-CPP. Wrap functions that can spuriously wake up in a loop for more information). To guarantee liveness, programs must test the while loop condition before invoking the condition_variable::wait() member function. This early test checks whether another thread has already satisfied the condition predicate and has sent a notification. Invoking wait() after the notification has been sent results in indefinite blocking.

...

In this example, all threads share a condition variable. Each thread has its own distinct condition predicate because each thread requires current_step to have a different value before proceeding. When the condition variable is signaled, any of the waiting threads can wake up. The following table illustrates a possible scenario in which the liveness property is violated. If, by chance, the notified thread is not the thread with the next step value, that thread will wait again. No additional notifications can occur, and eventually the pool of available threads will be exhausted.

...

This noncompliant code example violates the liveness property.

Compliant Solution (notify_all())

...

Awakening all threads guarantees the liveness property because each thread will execute its condition its condition predicate test, and exactly one will succeed and continue execution.

...

Another compliant solution is to use a unique condition variable for each thread (all associated with the same mutex). In this case, notify_one() wakes up only the thread that is waiting on it. This solution is more efficient than using notify_all() because only the desired thread is awakened.

Note that the condition the condition predicate of the signaled thread must be true; otherwise, a deadlock will occur.

...

Failing to preserve the thread safety and liveness of a program when using condition variables can lead to indefinite blocking and denial of service (DoS).

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

CON55-CPP

Low

Unlikely

Medium

P2

L3

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...