proxygen
fibers.h
Go to the documentation of this file.
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 /*
17  * This file serves as a helper for bridging folly fibers and python
18  * asyncio.future.
19  */
20 
21 #pragma once
22 
23 #include <Python.h>
24 #include <folly/Function.h>
26 
27 namespace folly {
28 namespace python {
29 
31  const folly::fibers::FiberManager::Options& opts = {});
32 
38 template <typename T>
40  folly::Function<T()>&& function,
41  folly::Function<void(folly::Try<T>&&, PyObject*)> callback,
42  PyObject* userData) {
43  auto* fiberManager = getFiberManager();
44  // We are handing over a pointer to a python object to c++ and need
45  // to make sure it isn't removed by python in that time.
46  Py_INCREF(userData);
47  auto guard = folly::makeGuard([=] { Py_DECREF(userData); });
48  fiberManager->addTask([function = std::move(function),
49  callback = std::move(callback),
50  userData,
51  guard = std::move(guard)]() mutable {
52  // This will run from inside the gil, called by the asyncio add_reader
53  auto res = folly::makeTryWith([&] { return function(); });
54  callback(std::move(res), userData);
55  // guard goes out of scope here, and its stored function is called
56  });
57 }
58 
59 } // namespace python
60 } // namespace folly
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
folly::std T
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
Single-threaded task execution engine.
GuardImpl guard(ErrorHandler &&handler)
Definition: Base.h:840
Definition: Try.h:51
FOLLY_NODISCARD detail::ScopeGuardImplDecay< F, true > makeGuard(F &&f) noexcept(noexcept(detail::ScopeGuardImplDecay< F, true >(static_cast< F && >(f))))
Definition: ScopeGuard.h:184
std::enable_if< !std::is_same< invoke_result_t< F >, void >::value, Try< invoke_result_t< F > > >::type makeTryWith(F &&f)
Definition: Try-inl.h:223
void bridgeFibers(folly::Function< T()> &&function, folly::Function< void(folly::Try< T > &&, PyObject *)> callback, PyObject *userData)
Definition: fibers.h:39
folly::fibers::FiberManager * getFiberManager(const folly::fibers::FiberManager::Options &opts)
Definition: fibers.cpp:24