promise.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. /**
  2. * Tencent is pleased to support the open source community by making Tars available.
  3. *
  4. * Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
  5. *
  6. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  7. * in compliance with the License. You may obtain a copy of the License at
  8. *
  9. * https://opensource.org/licenses/BSD-3-Clause
  10. *
  11. * Unless required by applicable law or agreed to in writing, software distributed
  12. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  13. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  14. * specific language governing permissions and limitations under the License.
  15. */
  16. #ifndef _TARS_PROMISE_H_
  17. #define _TARS_PROMISE_H_
  18. #include <memory>
  19. #include <mutex>
  20. #include <condition_variable>
  21. #include <vector>
  22. #include "promise/template_helper.h"
  23. #include "promise/exception.h"
  24. #include "promise/bind.h"
  25. namespace tars {
  26. // pre-declare future type.
  27. template <typename T> class Future;
  28. template <typename T> struct IsFutureType : std::false_type {};
  29. // only Future<T> is a future type.
  30. template <typename T> struct IsFutureType<Future<T> > : std::true_type {};
  31. // pre-declare promise type.
  32. template <typename T> class Promise;
  33. namespace promise {
  34. template <typename T> struct UnderlyType { using Type = T; };
  35. template <typename T> struct UnderlyType<Future<T> > { using Type = T; };
  36. template <typename T>
  37. struct FutureTypeTraits {
  38. using StorageType = std::shared_ptr<T>;
  39. using RValueType = const T&;
  40. using LValueType = const T&;
  41. using DestType = T&;
  42. static void init(StorageType& s, RValueType v)
  43. {
  44. s.reset(new T(v));
  45. }
  46. static void assign(DestType d, const StorageType& s)
  47. {
  48. d = *s;
  49. }
  50. };
  51. // since value maybe set in the future, there is no need to check type [const T&]
  52. template <typename T>
  53. struct FutureTypeTraits<T&> {
  54. using StorageType = T*;
  55. using RValueType = T&;
  56. using LValueType = T&;
  57. using DestType = T*&;
  58. static void init(StorageType& s, RValueType v)
  59. {
  60. s = &v;
  61. }
  62. static void assign(DestType d, const StorageType& s)
  63. {
  64. d = s;
  65. }
  66. };
  67. // void type.
  68. template <>
  69. struct FutureTypeTraits<void> {
  70. using RValueType = void;
  71. using LValueType = void;
  72. };
  73. template <typename T>
  74. class FutureInterface {
  75. public:
  76. using RValueType = typename FutureTypeTraits<T>::RValueType;
  77. using LValueType = typename FutureTypeTraits<T>::LValueType;
  78. using DestType = typename FutureTypeTraits<T>::DestType;
  79. using FutureType = std::shared_ptr<FutureInterface<T> >;
  80. using Watcher = Callback<void(const FutureType&)>;
  81. virtual ~FutureInterface() {}
  82. virtual bool isDone() const = 0;
  83. virtual bool hasValue() const = 0;
  84. virtual bool hasException() const = 0;
  85. virtual LValueType get() const = 0;
  86. virtual bool tryGet(DestType d) const = 0;
  87. virtual void setValue(RValueType v) = 0;
  88. virtual void setException(ExceptionPtr exp) = 0;
  89. virtual void appendWacther(const Watcher& watcher) = 0;
  90. protected:
  91. FutureInterface() {}
  92. };
  93. template <> class FutureInterface<void> {
  94. public:
  95. using RValueType = typename FutureTypeTraits<void>::RValueType;
  96. using LValueType = typename FutureTypeTraits<void>::LValueType;
  97. using FutureType = std::shared_ptr<FutureInterface<void> >;
  98. using Watcher = Callback<void(const FutureType&)>;
  99. virtual ~FutureInterface() {}
  100. virtual bool isDone() const = 0;
  101. virtual bool hasValue() const = 0;
  102. virtual bool hasException() const = 0;
  103. virtual LValueType get() const = 0;
  104. virtual void set() = 0;
  105. virtual void setException(ExceptionPtr exp) = 0;
  106. virtual void appendWacther(const Watcher& watcher) = 0;
  107. protected:
  108. FutureInterface() {}
  109. };
  110. template <typename T>
  111. class PromptFutureImpl final : public FutureInterface<T>
  112. , public std::enable_shared_from_this<PromptFutureImpl<T> > {
  113. public:
  114. using RValueType = typename FutureInterface<T>::RValueType;
  115. using LValueType = typename FutureInterface<T>::LValueType;
  116. using DestType = typename FutureInterface<T>::DestType;
  117. using Watcher = typename FutureInterface<T>::Watcher;
  118. PromptFutureImpl(RValueType v)
  119. : m_value()
  120. , m_exp()
  121. {
  122. FutureTypeTraits<T>::init(m_value, v);
  123. }
  124. PromptFutureImpl(ExceptionPtr exp)
  125. : m_value()
  126. , m_exp(exp)
  127. {
  128. }
  129. bool isDone() const override { return true; }
  130. bool hasValue() const override
  131. {
  132. if (m_exp)
  133. return false;
  134. return true;
  135. }
  136. bool hasException() const override
  137. {
  138. return (!!m_exp);
  139. }
  140. LValueType get() const override
  141. {
  142. if (m_exp)
  143. m_exp->rethrow();
  144. return *m_value;
  145. }
  146. bool tryGet(DestType d) const override
  147. {
  148. if (m_exp)
  149. m_exp->rethrow();
  150. FutureTypeTraits<T>::assign(d, m_value);
  151. return true;
  152. }
  153. void setValue(RValueType v) override
  154. {
  155. // do not touch this.
  156. }
  157. void setException(ExceptionPtr exp) override
  158. {
  159. // do not touch this.
  160. }
  161. void appendWacther(const Watcher& watcher) override
  162. {
  163. try {
  164. if (watcher)
  165. watcher.run(this->shared_from_this());
  166. } catch (...) {
  167. }
  168. }
  169. private:
  170. typename FutureTypeTraits<T>::StorageType m_value;
  171. ExceptionPtr m_exp;
  172. };
  173. template <> class PromptFutureImpl<void> final : public FutureInterface<void>
  174. , public std::enable_shared_from_this<PromptFutureImpl<void> > {
  175. public:
  176. using RValueType = typename FutureInterface<void>::RValueType;
  177. using LValueType = typename FutureInterface<void>::LValueType;
  178. using Watcher = typename FutureInterface<void>::Watcher;
  179. PromptFutureImpl()
  180. : m_exp()
  181. {
  182. }
  183. PromptFutureImpl(ExceptionPtr exp)
  184. : m_exp(exp)
  185. {
  186. }
  187. bool isDone() const override { return true; }
  188. bool hasValue() const override
  189. {
  190. if (m_exp)
  191. return false;
  192. return true;
  193. }
  194. bool hasException() const override
  195. {
  196. return (!!m_exp);
  197. }
  198. LValueType get() const override
  199. {
  200. if (m_exp)
  201. m_exp->rethrow();
  202. }
  203. void set() override
  204. {
  205. // do not touch this.
  206. }
  207. void setException(ExceptionPtr exp) override
  208. {
  209. // do not touch this.
  210. }
  211. void appendWacther(const Watcher& watcher) override
  212. {
  213. try {
  214. if (watcher)
  215. watcher.run(this->shared_from_this());
  216. } catch (...) {
  217. }
  218. }
  219. private:
  220. ExceptionPtr m_exp;
  221. };
  222. class FutureInternal {
  223. public:
  224. virtual ~FutureInternal() {}
  225. bool isDone() const
  226. {
  227. std::lock_guard<std::mutex> lock(m_mutex);
  228. return m_isDone;
  229. }
  230. bool hasValue() const
  231. {
  232. std::lock_guard<std::mutex> lock(m_mutex);
  233. return m_isDone && !m_exp;
  234. }
  235. bool hasException() const
  236. {
  237. std::lock_guard<std::mutex> lock(m_mutex);
  238. return m_isDone && m_exp;
  239. }
  240. void markFinishWithException(const ExceptionPtr& exp)
  241. {
  242. {
  243. std::lock_guard<std::mutex> lock(m_mutex);
  244. if (m_isDone)
  245. throw Exception("Duplicated mark finish with exception.");
  246. m_isDone = true;
  247. m_exp = exp;
  248. }
  249. m_cv.notify_all();
  250. }
  251. void wait() const
  252. {
  253. {
  254. std::unique_lock<std::mutex> lock(m_mutex);
  255. m_cv.wait(lock, [&]{ return m_isDone; });
  256. }
  257. if (m_exp)
  258. m_exp->rethrow();
  259. }
  260. protected:
  261. FutureInternal()
  262. : m_mutex()
  263. , m_cv()
  264. , m_isDone(false)
  265. , m_exp()
  266. {
  267. }
  268. mutable std::mutex m_mutex;
  269. mutable std::condition_variable m_cv;
  270. bool m_isDone;
  271. ExceptionPtr m_exp;
  272. };
  273. template <typename T>
  274. class FutureImpl : public FutureInterface<T>
  275. , public std::enable_shared_from_this<FutureImpl<T> >
  276. , private FutureInternal {
  277. public:
  278. using RValueType = typename FutureInterface<T>::RValueType;
  279. using LValueType = typename FutureInterface<T>::LValueType;
  280. using DestType = typename FutureInterface<T>::DestType;
  281. using Watcher = typename FutureInterface<T>::Watcher;
  282. FutureImpl()
  283. : m_value()
  284. , m_watchers()
  285. {
  286. }
  287. bool isDone() const override { return FutureInternal::isDone(); }
  288. bool hasValue() const override { return FutureInternal::hasValue(); }
  289. bool hasException() const override { return FutureInternal::hasException(); }
  290. LValueType get() const override
  291. {
  292. wait();
  293. return *m_value;
  294. }
  295. bool tryGet(DestType d) const override
  296. {
  297. if (!FutureInternal::isDone())
  298. return false;
  299. if (m_exp)
  300. m_exp->rethrow();
  301. FutureTypeTraits<T>::assign(d, m_value);
  302. return true;
  303. }
  304. void setValue(RValueType v) override
  305. {
  306. {
  307. // FixMe: move this to FutureInternal.
  308. std::lock_guard<std::mutex> lock(m_mutex);
  309. if (m_isDone)
  310. throw Exception("Duplicated set value.");
  311. m_isDone = true;
  312. FutureTypeTraits<T>::init(m_value, v);
  313. }
  314. m_cv.notify_all();
  315. invokeWatchers();
  316. }
  317. void setException(ExceptionPtr exp) override
  318. {
  319. markFinishWithException(exp);
  320. invokeWatchers();
  321. }
  322. void appendWacther(const Watcher& watcher) override
  323. {
  324. if (!watcher)
  325. return;
  326. if (FutureInternal::isDone()) {
  327. try {
  328. if (watcher)
  329. watcher.run(this->shared_from_this());
  330. } catch (...) {
  331. }
  332. } else {
  333. std::lock_guard<std::mutex> lock(m_mutex);
  334. m_watchers.push_back(watcher);
  335. }
  336. }
  337. protected:
  338. void invokeWatchers()
  339. {
  340. std::vector<Watcher> watchers;
  341. {
  342. std::lock_guard<std::mutex> lock(m_mutex);
  343. watchers.swap(m_watchers);
  344. }
  345. for (const Watcher& w : watchers) {
  346. try {
  347. w.run(this->shared_from_this());
  348. } catch (...) {
  349. }
  350. }
  351. }
  352. typename FutureTypeTraits<T>::StorageType m_value;
  353. std::vector<Watcher> m_watchers;
  354. };
  355. template <> class FutureImpl<void> : public FutureInterface<void>
  356. , public std::enable_shared_from_this<FutureImpl<void> >
  357. , private FutureInternal {
  358. public:
  359. using RValueType = typename FutureInterface<void>::RValueType;
  360. using LValueType = typename FutureInterface<void>::LValueType;
  361. using Watcher = typename FutureInterface<void>::Watcher;
  362. FutureImpl()
  363. : m_watchers()
  364. {
  365. }
  366. bool isDone() const override { return FutureInternal::isDone(); }
  367. bool hasValue() const override { return FutureInternal::hasValue(); }
  368. bool hasException() const override { return FutureInternal::hasException(); }
  369. LValueType get() const override
  370. {
  371. wait();
  372. }
  373. void set() override
  374. {
  375. {
  376. // FixMe: move this to FutureInternal.
  377. std::lock_guard<std::mutex> lock(m_mutex);
  378. if (m_isDone)
  379. throw Exception("Duplicated set finish.");
  380. m_isDone = true;
  381. }
  382. m_cv.notify_all();
  383. invokeWatchers();
  384. }
  385. void setException(ExceptionPtr exp) override
  386. {
  387. markFinishWithException(exp);
  388. invokeWatchers();
  389. }
  390. void appendWacther(const Watcher& watcher) override
  391. {
  392. if (!watcher)
  393. return;
  394. if (FutureInternal::isDone()) {
  395. try {
  396. if (watcher)
  397. watcher.run(this->shared_from_this());
  398. } catch (...) {
  399. }
  400. } else {
  401. std::lock_guard<std::mutex> lock(m_mutex);
  402. m_watchers.push_back(watcher);
  403. }
  404. }
  405. protected:
  406. void invokeWatchers()
  407. {
  408. std::vector<Watcher> watchers;
  409. {
  410. std::lock_guard<std::mutex> lock(m_mutex);
  411. watchers.swap(m_watchers);
  412. }
  413. for (const Watcher& w : watchers) {
  414. try {
  415. w.run(this->shared_from_this());
  416. } catch (...) {
  417. }
  418. }
  419. }
  420. std::vector<Watcher> m_watchers;
  421. };
  422. // support sequential watchers.
  423. template <typename T> class ForwardWatcher;
  424. template <typename R, typename T> class SequentialWatcher {
  425. using ValueType = typename UnderlyType<R>::Type;
  426. using FuturePtr = std::shared_ptr<FutureInterface<T> >;
  427. using Watcher = Callback<R(const Future<T>&)>;
  428. public:
  429. SequentialWatcher(const Watcher& w, const Promise<ValueType>& p)
  430. : m_watcher(w)
  431. , m_promise(p)
  432. {
  433. }
  434. template <typename U>
  435. enable_if_t<std::is_void<U>::value> invoke(const FuturePtr& future)
  436. {
  437. try {
  438. m_watcher.run(future);
  439. m_promise.set();
  440. } catch (...) {
  441. m_promise.setException(currentException());
  442. }
  443. }
  444. template <typename U>
  445. enable_if_t<!std::is_void<U>::value && !IsFutureType<U>::value> invoke(const FuturePtr& future)
  446. {
  447. try {
  448. m_promise.setValue(m_watcher.run(future));
  449. } catch (...) {
  450. m_promise.setException(currentException());
  451. }
  452. }
  453. template <typename U>
  454. enable_if_t<IsFutureType<U>::value> invoke(const FuturePtr& future)
  455. {
  456. try {
  457. // sequential watcher.
  458. m_watcher.run(future).then(Bind(&ForwardWatcher<ValueType>::template invoke<ValueType>,
  459. std::make_shared<ForwardWatcher<ValueType> >(m_promise)));
  460. } catch (...) {
  461. m_promise.setException(currentException());
  462. }
  463. }
  464. protected:
  465. Watcher m_watcher;
  466. Promise<ValueType> m_promise;
  467. };
  468. template <typename R>
  469. class ForwardWatcher {
  470. public:
  471. ForwardWatcher(const Promise<R>& p)
  472. : m_promise(p)
  473. {
  474. }
  475. template <typename V>
  476. enable_if_t<std::is_void<V>::value> invoke(const Future<V>& future)
  477. {
  478. try {
  479. future.get();
  480. m_promise.set();
  481. } catch (...) {
  482. m_promise.setException(currentException());
  483. }
  484. }
  485. template <typename V>
  486. enable_if_t<!std::is_void<V>::value> invoke(const Future<V>& future)
  487. {
  488. try {
  489. m_promise.setValue(future.get());
  490. } catch (...) {
  491. m_promise.setException(currentException());
  492. }
  493. }
  494. protected:
  495. Promise<R> m_promise;
  496. };
  497. template <typename T>
  498. class FutureBase {
  499. public:
  500. using LValueType = typename FutureTypeTraits<T>::LValueType;
  501. FutureBase()
  502. : m_future()
  503. {
  504. }
  505. FutureBase(ExceptionPtr exp)
  506. : m_future(new PromptFutureImpl<T>(exp))
  507. {
  508. }
  509. virtual ~FutureBase() {}
  510. LValueType get() const
  511. {
  512. if (!m_future)
  513. throw Exception("future uninitialized");
  514. return m_future->get();
  515. }
  516. bool isDone() const
  517. {
  518. if (!m_future)
  519. return false;
  520. return m_future->isDone();
  521. }
  522. bool hasValue() const
  523. {
  524. if (!m_future)
  525. return false;
  526. return m_future->hasValue();
  527. }
  528. bool hasException() const
  529. {
  530. if (!m_future)
  531. return false;
  532. return m_future->hasException();
  533. }
  534. // safe bool idiom
  535. // refer: https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Safe_bool
  536. // c++11 standard
  537. explicit operator bool() const
  538. {
  539. return m_future ? true : false;
  540. }
  541. protected:
  542. using FuturePtr = std::shared_ptr<FutureInterface<T> >;
  543. FutureBase(const FuturePtr& future)
  544. : m_future(future)
  545. {
  546. }
  547. FuturePtr m_future;
  548. };
  549. } // end namespace promise
  550. template <typename T>
  551. class Future : public promise::FutureBase<T> {
  552. public:
  553. explicit Future(typename promise::FutureTypeTraits<T>::RValueType v)
  554. : promise::FutureBase<T>(new promise::PromptFutureImpl<T>(v))
  555. {
  556. }
  557. Future(ExceptionPtr exp)
  558. : promise::FutureBase<T>(exp)
  559. {
  560. }
  561. // can be initialize in tuple.
  562. Future() = default;
  563. ~Future() override {}
  564. template <typename R>
  565. Future<typename promise::UnderlyType<R>::Type> then(const Callback<R(const Future<T>&)>& watcher)
  566. {
  567. using ValueType = typename promise::UnderlyType<R>::Type;
  568. if (!this->m_future)
  569. throw Exception("future uninitialized");
  570. Promise<ValueType> promise;
  571. this->m_future->appendWacther(Bind(&promise::SequentialWatcher<R, T>::template invoke<R>,
  572. std::make_shared<promise::SequentialWatcher<R, T> >(watcher, promise)));
  573. return promise.getFuture();
  574. }
  575. private:
  576. using FuturePtr = typename promise::FutureBase<T>::FuturePtr;
  577. Future(const FuturePtr& future)
  578. : promise::FutureBase<T>(future)
  579. {
  580. }
  581. template <typename U, typename V> friend class promise::SequentialWatcher;
  582. friend class Promise<T>;
  583. };
  584. template <> class Future<void> : public promise::FutureBase<void> {
  585. public:
  586. // can be initialize in tuple.
  587. Future() = default;
  588. Future(ExceptionPtr exp)
  589. : promise::FutureBase<void>(exp)
  590. {
  591. }
  592. ~Future() override {}
  593. template <typename R>
  594. Future<typename promise::UnderlyType<R>::Type> then(const Callback<R(const Future<void>&)>& watcher)
  595. {
  596. using ValueType = typename promise::UnderlyType<R>::Type;
  597. if (!this->m_future)
  598. throw Exception("future uninitialized");
  599. Promise<ValueType> promise;
  600. this->m_future->appendWacther(Bind(&promise::SequentialWatcher<R, void>::template invoke<R>,
  601. std::make_shared<promise::SequentialWatcher<R, void> >(watcher, promise)));
  602. return promise.getFuture();
  603. }
  604. private:
  605. using FuturePtr = typename promise::FutureBase<void>::FuturePtr;
  606. Future(const FuturePtr& future)
  607. : promise::FutureBase<void>(future)
  608. {
  609. }
  610. template <typename U, typename V> friend class promise::SequentialWatcher;
  611. friend class Promise<void>;
  612. };
  613. template <typename T>
  614. class Promise final {
  615. public:
  616. using ValueType = typename promise::UnderlyType<T>::Type;
  617. Promise()
  618. : m_future(new promise::FutureImpl<ValueType>())
  619. {
  620. }
  621. void setValue(typename promise::FutureTypeTraits<T>::RValueType v)
  622. {
  623. m_future->setValue(v);
  624. }
  625. void setException(const ExceptionPtr& e)
  626. {
  627. m_future->setException(e);
  628. }
  629. Future<ValueType> getFuture()
  630. {
  631. return m_future;
  632. }
  633. private:
  634. std::shared_ptr<promise::FutureInterface<ValueType> > m_future;
  635. };
  636. template <> class Promise<void> final {
  637. public:
  638. Promise()
  639. : m_future(new promise::FutureImpl<void>())
  640. {
  641. }
  642. void set()
  643. {
  644. m_future->set();
  645. }
  646. void setException(const ExceptionPtr& e)
  647. {
  648. m_future->setException(e);
  649. }
  650. Future<void> getFuture()
  651. {
  652. return m_future;
  653. }
  654. private:
  655. std::shared_ptr<promise::FutureInterface<void> > m_future;
  656. };
  657. } // end namespace tars
  658. #endif