C & C++

C & C++

Made by DeepSource

Possibly bad use of cnd_wait, cnd_timedwait, wait, wait_for, or wait_until function calls CXX-E2002

Bug risk
Major

Found cnd_wait, cnd_timedwait, wait, wait_for, or wait_until function calls when the function is not invoked from a loop that checks whether a condition predicate holds or the function has a condition parameter.

To fix this issue, ensure that the function call is wrapped in a loop that checks the condition predicate or has a condition parameter. This will prevent spurious wake-ups and ensure correct behavior.

Bad Practice

#include <condition_variable>
#include <thread>

struct Node1 {
  void* Node1;
  struct Node1* next;
};

static Node1 list;
static std::mutex m;
static std::condition_variable c;

void foo() {
  std::unique_lock<std::mutex> lk(m);
  std::condition_variable& condition = c;
  if (list.next == nullptr) {
    condition.wait(lk); // consider using while loop instead
  }
}

Recommended

#include <condition_variable>
#include <thread>

struct Node1 {
  void* Node1;
  struct Node1* next;
};

static Node1 list;
static std::mutex m;
static std::condition_variable c;

void foo() {
  std::unique_lock<std::mutex> lk(m);
  std::condition_variable& condition = c;
  while (list.next == nullptr) {
    condition.wait(lk);
  }
}