Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: blanklines

...

Code Block
bgColor#FFcccc
langc
#include <condition_variable>
#include <mutex>
 
struct Node {
  void *node;
  struct Node *next;
};
  
static Node list;
static std::mutex m;
static std::condition_variable condition;
  
void consume_list_element(std::condition_variable &condition) {
  std::unique_lock<std::mutex> lk(m);
  
  if (list.next) {
    condition.wait(lk);
  }
 
  // Proceed when condition holds.
 
}

Compliant Solution (Explicit loop with predicate)

...

Code Block
bgColor#ccccff
langc
#include <condition_variable>
#include <mutex>
 
struct Node {
  void *node;
  struct Node *next;
};
  
static Node list;
static std::mutex m;
static std::condition_variable condition;
  
void consume_list_element() {
  std::unique_lock<std::mutex> lk(m);
  
  while (list.next) {
    condition.wait(lk);
  }
 
  // Proceed when condition holds.
 
}

Compliant Solution (Implicit loop with lambda predicate)

...

Code Block
bgColor#ccccff
langc
#include <condition_variable>
#include <mutex>
 
struct Node {
  void *node;
  struct Node *next;
};
  
static Node list;
static std::mutex m;
static std::condition_variable condition;
  
void consume_list_element() {
  std::unique_lock<std::mutex> lk(m);
 
  condition.wait(lk, []{ return !list.next; });
  // Proceed when condition holds.
 
}

Risk Assessment

Failure to enclose calls to the wait(), wait_for(), or wait_until() member functions inside a while loop can lead to indefinite blocking and denial of service (DoS).

...