gpt4 book ai didi

c++ - 我如何使用 timed_mutex?

转载 作者:行者123 更新时间:2023-11-30 01:40:47 26 4
gpt4 key购买 nike

我第一次使用 timed_mutex。到目前为止,它对我来说只是 lock_guard

但似乎只有第一个try_lock_for真正成功了。除了第一个 try_lock_for 之外的所有内容都返回 false:

#include <chrono>
#include <future>
#include <mutex>
#include <vector>
#include <iostream>
std::timed_mutex mtx;
long fibX(long n) { return n < 2L ? 1L : fibX(n-1L) + fibX(n-2L); }
long fibCall(long n) {
using namespace std::chrono;
if(mtx.try_lock_for(1000ms)) { // <<< HERE
return fibX(n);
mtx.unlock();
} else {
return 0L;
}
}
int main() {
std::vector< std::future<long> > fs;
for(long n=1; n<= 42; ++n) {
fs.emplace_back( std::async(std::launch::async, fibCall, n) );
}
for(auto &f : fs) {
std::cout << f.get() << "\n";
}
}

我得到结果 1, 0, 0, 0, 0, ...

但我希望从 0 开始得到 1, 2, 3, 5, 8, 13, ... 0, 0, 0, 0, 0当第一个调用花费的时间超过一秒时。

可能是一些愚蠢的错误,但我看不到它...

最佳答案

if(mtx.try_lock_for(1000ms)) {    // <<< HERE
return fibX(n);
mtx.unlock();

自从您return 后,您的unlock 永远不会执行。

关于c++ - 我如何使用 timed_mutex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42635960/

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