1
我第一次使用timed_mutex
工作。到目前爲止,我只有lock_guard
。如何使用timed_mutex?
但似乎只有第一個try_lock_for
實際上成功。除了第一個try_lock_for
返回錯誤:
#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, ...
但我希望得到1, 2, 3, 5, 8, 13, ... 0, 0, 0, 0, 0
與0
首發在第一次調用花費更長的時間,然後一秒鐘。
也許有些愚蠢的錯誤,但我不能看到它... ...
如何emberassing ... – towi