lundi 26 octobre 2020

Condition variable python with statement in C++ [duplicate]

From the Python threading documentation about Condition objects I try to find how I would do it in C++. What's interesting me is when a Python code is using a with statement on a Condition object like:

cv = threading.Condition()
with cv:
  ...

If under the with statement there is only code, I don't have any issue understanding how I could do it, I think, using a std::lock_guard would do to me. But what bugs me is when there is a wait call:

cv = threading.Condition()
with cv:
  cv.wait(timeout)

What I don't understand is that the Condition documentation states:

A condition variable obeys the context management protocol: using the with statement acquires the associated lock for the duration of the enclosed block. The acquire() and release() methods also call the corresponding methods of the associated lock.

So what's the point in locking itself and wait? In C++ do I have to do the same?

std::condition_variable cv;
std::mutex m;
{
  std::lock_guard<std::mutex> lk(m);
  std::unique_lock<std::mutex> ul(m);
  cv.wait_for(ul, std::chrono::seconds(timeout));
}

Aucun commentaire:

Enregistrer un commentaire