gpt4 book ai didi

c++ - 如何使用 condition_variable 来真正 wait_for 不超过一定的持续时间

转载 作者:IT老高 更新时间:2023-10-28 23:01:42 25 4
gpt4 key购买 nike

作为 it turns out , condition_variable::wait_for 真的应该叫 condition_variable::wait_for_or_possibly_indefinitely_longer_than,因为它需要在真正超时和返回之前重新获取锁。

this program进行演示。

有没有办法表达,“看,我真的只有 2 秒。如果当时 myPredicate() 仍然是假的和/或锁是仍然被锁定,我不在乎,只要继续,给我一个方法来检测它。”

类似:

bool myPredicate();
auto sec = std::chrono::seconds(1);

bool pred;
std::condition_variable::cv_status timedOut;

std::tie( pred, timedOut ) =
cv.really_wait_for_no_longer_than( lck, 2*sec, myPredicate );

if( lck.owns_lock() ) {
// Can use mutexed resource.
// ...
lck.unlock();
} else {
// Cannot use mutexed resource. Deal with it.
};

最佳答案

我认为您误用了 condition_variable 的锁。这只是为了保护条件,而不是为了保护耗时的工作。

您的示例可以通过将 mutex 分成两部分来轻松修复 - 一个用于关键部分,另一个用于保护对 ready 条件的修改。这是修改后的片段:

typedef std::unique_lock<std::mutex> lock_type;
auto sec = std::chrono::seconds(1);
std::mutex mtx_work;
std::mutex mtx_ready;
std::condition_variable cv;
bool ready = false;

void task1() {
log("Starting task 1. Waiting on cv for 2 secs.");
lock_type lck(mtx_ready);
bool done = cv.wait_for(lck, 2*sec, []{log("Checking condition..."); return ready;});
std::stringstream ss;
ss << "Task 1 finished, done==" << (done?"true":"false") << ", " << (lck.owns_lock()?"lock owned":"lock not owned");
log(ss.str());
}

void task2() {
// Allow task1 to go first
std::this_thread::sleep_for(1*sec);
log("Starting task 2. Locking and sleeping 2 secs.");
lock_type lck1(mtx_work);
std::this_thread::sleep_for(2*sec);
lock_type lck2(mtx_ready);
ready = true; // This happens around 3s into the program
log("OK, task 2 unlocking...");
lck2.unlock();
cv.notify_one();
}

它的输出:

@2 ms: Starting task 1. Waiting on cv for 2 secs.
@2 ms: Checking condition...
@1002 ms: Starting task 2. Locking and sleeping 2 secs.
@2002 ms: Checking condition...
@2002 ms: Task 1 finished, done==false, lock owned
@3002 ms: OK, task 2 unlocking...

关于c++ - 如何使用 condition_variable 来真正 wait_for 不超过一定的持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25194633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com