futures.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright 2016-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. /*
  17. * This file serves as a helper for bridging folly::future and python
  18. * asyncio.future.
  19. */
  20. #pragma once
  21. #include <Python.h>
  22. #include <folly/Executor.h>
  23. #include <folly/futures/Future.h>
  24. #include <folly/python/AsyncioExecutor.h>
  25. #include <folly/python/executor_api.h>
  26. namespace folly {
  27. namespace python {
  28. inline folly::Executor* getExecutor() {
  29. import_folly__executor();
  30. return get_executor();
  31. }
  32. template <typename T>
  33. void bridgeFuture(
  34. folly::Executor* executor,
  35. folly::Future<T>&& futureFrom,
  36. folly::Function<void(folly::Try<T>&&, PyObject*)> callback,
  37. PyObject* userData) {
  38. // We are handing over a pointer to a python object to c++ and need
  39. // to make sure it isn't removed by python in that time.
  40. Py_INCREF(userData);
  41. auto guard = folly::makeGuard([=] { Py_DECREF(userData); });
  42. // Handle the lambdas for cython
  43. // run callback from our Q
  44. futureFrom.via(executor).then(
  45. [callback = std::move(callback), userData, guard = std::move(guard)](
  46. folly::Try<T>&& res) mutable {
  47. // This will run from inside the gil, called by the asyncio add_reader
  48. callback(std::move(res), userData);
  49. // guard goes out of scope here, and its stored function is called
  50. });
  51. }
  52. template <typename T>
  53. void bridgeFuture(
  54. folly::Future<T>&& futureFrom,
  55. folly::Function<void(folly::Try<T>&&, PyObject*)> callback,
  56. PyObject* userData) {
  57. bridgeFuture(
  58. getExecutor(), std::move(futureFrom), std::move(callback), userData);
  59. }
  60. } // namespace python
  61. } // namespace folly