简体   繁体   中英

How do I use a timed_mutex?

I work for the first time with timed_mutex . Up until now it was only lock_guard for me.

But it seems that only the first try_lock_for actually succeeds. All but the first 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";
    }
}

I get the results 1, 0, 0, 0, 0, ...

But I expected to get 1, 2, 3, 5, 8, 13, ... 0, 0, 0, 0, 0 starting with 0 s when the first call takes longer then one second.

Probably some stupid error, but I can not see it...

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

Your unlock never executes since you return .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM