시나리오 :
나는이 condition_variable 기반 대기 및 신호 메커니즘을. 작동합니다! 그러나 저는 고전적인 대기 및 신호 메커니즘 이상의 것이 필요합니다. 나는 "동시에 condition_variable
" 무한한 기다릴뿐만 아니라 시간 제한을 기다릴 수 있어야한다 . 따라서 condition_variable
가짜 깨우기 문제도 처리 하는 래퍼 클래스를 만들었 습니다. 다음은 이에 대한 코드입니다.
암호:
// CondVarWrapper.hpp
#pragma once
#include <mutex>
#include <chrono>
#include <condition_variable>
class CondVarWrapper {
public:
void Signal() {
std::unique_lock<std::mutex> unique_lock(cv_mutex);
cond_var_signalled = true;
timed_out = false;
unique_lock.unlock();
cond_var.notify_one();
}
bool WaitFor(const std::chrono::seconds timeout) {
std::unique_lock<std::mutex> unique_lock(cv_mutex);
timed_out = true;
cond_var.wait_for(unique_lock, timeout, [this] {
return cond_var_signalled;
});
cond_var_signalled = false;
return (timed_out == false);
}
bool Wait() {
std::unique_lock<std::mutex> unique_lock(cv_mutex);
timed_out = true;
cond_var.wait(unique_lock, [this] {
return cond_var_signalled;
});
cond_var_signalled = false;
return (timed_out == false);
}
private:
bool cond_var_signalled = false;
bool timed_out = false;
std::mutex cv_mutex;
std::condition_variable cond_var;
};
// main.cpp
#include "CondVarWrapper.hpp"
#include <iostream>
#include <string>
#include <thread>
int main() {
CondVarWrapper cond_var_wrapper;
std::thread my_thread = std::thread([&cond_var_wrapper]{
std::cout << "Thread started" << std::endl;
if (cond_var_wrapper.WaitFor(std::chrono::seconds(10))) {
std::cout << "Thread stopped by signal from main" << std::endl;
} else {
std::cout << "ERROR: Thread stopping because of timeout" << std::endl;
}
});
std::this_thread::sleep_for(std::chrono::seconds(3));
// Uncomment following line to see the timeout working
cond_var_wrapper.Signal();
my_thread.join();
}
질문 :
위의 코드는 좋지만 한 가지 문제가 있다고 생각합니까? 내가 정말 할 수 있을까 wait
잘 할뿐 wait_for
동일한에 condition_variable
? 스레드가 cv_mutex
호출에 의해 획득 되고 CondVarWrapper::Wait()
어떤 이유로이 스레드가 반환되지 않으면 어떻게 될까요? 그런 다음 다른 스레드가 CondVarWrapper::WaitFor(std::chrono::seconds(3))
3 초 내에 성공하지 못하면 반환 될 것으로 예상하여 호출 합니다. 자,이 두 번째 쓰레드는 WaitFor
3 초 후에 돌아올 수 없습니다 . 사실 그것은 결코 돌아 오지 않을 것입니다. 때문에 condition_variable
대기가 시간 제한 대기 아니라에 대한 잠금입니다 cv_mutex
. 내가 맞습니까, 아니면 여기서 이해가 틀렸습니까?
위의 내용이 정확하면 std::mutex cv_mutex
a 로 교체 std::timed_mutex cv_mutex
하고 timed_wait를 CondVarWrapper::WaitFor
수행하고 무한 대기를 수행해야 CondVarWrapper::Wait
합니까? 아니면 더 나은 / 쉬운 처리 방법이 있습니까?
std::condition::wait
조건 변수를 호출하면 뮤텍스가 해제됩니다 cond_var
. 따라서 CondVarWrapper::Wait
한 스레드에서 호출 할 때 호출 할 때 뮤텍스를 해제하고 std::condition::wait
거기에 영원히 멈추고 두 번째 스레드는 여전히 CondVarWrapper::WaitFor
뮤텍스를 호출 하고 성공적으로 잠글 수 있습니다 cv_mutex
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다