我看到Qt有future类,它是boost::future的直接模拟类,但是什么是boost::promise的qt?什么是Qt for boost :: promise <T>?
回答
boost :: promises是设置期货价值的手段。在Qt中,你不能设置期货,你可以只有退货。这是未来“设置”数据的唯一方法。
因此,为了设置未来的数据,您必须从QtConcurrent::run
调用的函数返回它。要做到这一点,你需要使用任何Qt的线程间通信机制 - 事件,受互斥锁保护的变量等。你必须告诉运行代码的线程,该线程将返回未来将返回的未来。这是实现承诺所能做到的唯一方式。
唉,如果你想进入无证领土,然后将下面的代码做什么boost::promise::setValue
会:
QFuture<int> f;
int i = 1;
...
f.d.reportResult(&i);
// or
f.d.reportFinished(&i);
我没有打扰检查,如果它的工作原理(还)。
'd'成员的文档说'//警告:d指针没有记录并且被认为是私有的,所以这可能不是要走的路。 –
@JamesHenstridge如果你选择这样做,这是一条路,但当然首选解决方案在前面的段落中。 –
如果没有QtConcurrent助手可以满足您的需求,那么使用'QFutureInterface'(就像在其他答案中一样)可能是更好的选择。它似乎被视为是半公开的,并且在最早的Qt 6之前不会改变:http://lists.qt-project.org/pipermail/development/2015-July/022572.html –
构建我自己的QFuture,如接受的答案中所示,对我而言并不适用。起初,它似乎在工作,但在我的测试中,我意识到它没有阻止来电者。哎呦!所以我深入研究了一下代码,发现QFutureInterface就是你想用作'承诺'的东西。像boost :: promise一样,QFutureInterface是您在工作线程中与之交互的内容,它是QFutures的工厂。
所以这里是我一直在Qt 4.8中做的(不知道这是否适用于更高版本)。
QFutureInterface<QVariant> promise;
promise.reportStarted();
...
promise.reportResult(someVariant);
promise.reportFinished();
在客户端线程
然后,假设你有机会获得QFutureInterface“承诺”
QVariant result = promise.future().result();
的future()
调用创建绑定到一个QFutureInterface一个QFuture工厂方法。如果需要,您应该可以获得QFuture并在以后拨打result()
。
没有正式的Qt模拟但也有实现的承诺(或类似的模式)的几个社区图书馆:
- 本Lau的AsyncFuture(benlau/asyncfuture)
基于无证QFutureInterface
LatencyMachine在his answer已经提到。
它不完全是一种承诺模式,而是一种观察者模式。 - Benoit Walter的QtPromise(bwalter/qt-promise)
部分基于Ben Lau的AsyncFuture。 - 西蒙·布鲁内尔QtPromise(simonbrunel/qtpromise)
- 我QtPromise(julrich/QtPromise)
免责声明:我是作者。
- 1. 在TypeScript中,定义可返回Promise <T>或Promise <T[]>的函数的最佳方法是什么?
- 2. 为什么boost :: call_traits <double> :: param_type是“const double&”,而不是“double”
- 3. Qt - 什么是QApplication?
- 4. 什么是瞬间<2>在boost :: accumulators中的含义
- 5. “cout <<(_ 1 * 3)”是什么意思?
- 6. boost :: multi_index_container :: index <Tag> :: type是什么意思?
- 7. boost :: program_options :: notify()是什么?
- 8. Boost中的pthread是什么?
- 9. boost :: heap :: arity,它是什么?
- 10. C++什么是std :: shared_future和std :: promise
- 11. 为什么不是'Promise Chaining'工作?
- 12. C++:什么是:: for?
- 13. 什么是android:includeFontPadding for?
- 14. 什么是MemoryCache.AddOrGetExisting for?
- 15. 什么是。$ for CKEditor?
- 16. Java |什么是/ ** */for?
- 17. 什么是<NS0:什么?
- 18. std :: to_string,boost :: to_string和boost :: lexical_cast <std::string>有什么区别?
- 19. 什么是boost的shared_ptr(shared_ptr <Y> const&r,T * p)用于?
- 20. 为什么在boost :: array <char,8192>中必须是8192?
- 21. 什么是一个好的返回类型`boost :: shared_ptr <StructA>`?
- 22. Resolving Promise <pending>
- 23. 为什么boost :: is_same <int const&,boost :: add_const <int &> :: value等于false?
- 24. 为什么我的程序在boost :: enable_shared_from_this <>/boost :: shared_ptr <>中崩溃?
- 25. wcout << L是什么?
- 26. Promise的TypeScript参数<T>,Why not Promise <T1,T2>?
- 27. 什么是Qt的配置
- 28. 什么是Qt端口?
- 29. Qt DropActions:什么是ActionMask?
- 30. Qt的 - 什么是代码
这是一个承诺。 – 2012-06-04 01:26:19