如何使用 timed_mutex?

How do I use a timed_mutex?

我第一次与 timed_mutex 一起工作。到现在为止对我来说只有 lock_guard

但似乎只有第一个try_lock_for真正成功了。除了第一个 try_lock_for return 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();

您的 unlock 自从您 return 以来从未执行过。