composition_3.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright 2018-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <algorithm>
  17. #include <cassert>
  18. #include <iostream>
  19. #include <vector>
  20. #include <folly/experimental/pushmi/o/defer.h>
  21. #include <folly/experimental/pushmi/o/share.h>
  22. #include <folly/experimental/pushmi/o/just.h>
  23. #include <folly/experimental/pushmi/o/tap.h>
  24. // https://godbolt.org/g/rVLMTu
  25. using namespace pushmi::aliases;
  26. // three models of submission deferral
  27. // (none of these use an executor, they are all running
  28. // synchronously on the main thread)
  29. // this constructs eagerly and submits just() lazily
  30. auto defer_execution() {
  31. printf("construct just\n");
  32. return op::just(42) | op::tap([](int v) { printf("just - %d\n", v); });
  33. }
  34. // this constructs defer() eagerly, constructs just() and submits just() lazily
  35. auto defer_construction() {
  36. return op::defer([] { return defer_execution(); });
  37. }
  38. // this constructs defer(), constructs just() and submits just() eagerly
  39. auto eager_execution() {
  40. return defer_execution() | op::share<int>();
  41. }
  42. int main() {
  43. printf("\ncall defer_execution\n");
  44. auto de = defer_execution();
  45. printf("submit defer_execution\n");
  46. de | op::submit();
  47. // call defer_execution
  48. // construct just
  49. // submit defer_execution
  50. // just - 42
  51. printf("\ncall defer_construction\n");
  52. auto dc = defer_construction();
  53. printf("submit defer_construction\n");
  54. dc | op::submit();
  55. // call defer_construction
  56. // submit defer_construction
  57. // construct just
  58. // just - 42
  59. printf("\ncall eager_execution\n");
  60. auto ee = eager_execution();
  61. printf("submit eager_execution\n");
  62. ee | op::submit();
  63. // call eager_execution
  64. // construct just
  65. // just - 42
  66. // submit eager_execution
  67. std::cout << "OK" << std::endl;
  68. // OK
  69. }