proxygen
FibersTestApp.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2014-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 <iostream>
17 #include <queue>
18 
19 #include <folly/Memory.h>
20 
23 
24 using namespace folly::fibers;
25 
26 struct Application {
27  public:
29  : fiberManager(std::make_unique<SimpleLoopController>()),
30  toSend(20),
31  maxOutstanding(5) {}
32 
33  void loop() {
34  if (pendingRequests.size() == maxOutstanding || toSend == 0) {
35  if (pendingRequests.empty()) {
36  return;
37  }
38  intptr_t value = rand() % 1000;
39  std::cout << "Completing request with data = " << value << std::endl;
40 
41  pendingRequests.front().setValue(value);
42  pendingRequests.pop();
43  } else {
44  static size_t id_counter = 1;
45  size_t id = id_counter++;
46  std::cout << "Adding new request with id = " << id << std::endl;
47 
48  fiberManager.addTask([this, id]() {
49  std::cout << "Executing fiber with id = " << id << std::endl;
50 
51  auto result1 = await([this](Promise<int> fiber) {
52  pendingRequests.push(std::move(fiber));
53  });
54 
55  std::cout << "Fiber id = " << id << " got result1 = " << result1
56  << std::endl;
57 
58  auto result2 = await([this](Promise<int> fiber) {
59  pendingRequests.push(std::move(fiber));
60  });
61  std::cout << "Fiber id = " << id << " got result2 = " << result2
62  << std::endl;
63  });
64 
65  if (--toSend == 0) {
66  auto& loopController =
67  dynamic_cast<SimpleLoopController&>(fiberManager.loopController());
68  loopController.stop();
69  }
70  }
71  }
72 
74 
75  std::queue<Promise<int>> pendingRequests;
76  size_t toSend;
78 };
79 
80 int main() {
81  Application app;
82 
83  auto loop = [&app]() { app.loop(); };
84 
85  auto& loopController =
86  dynamic_cast<SimpleLoopController&>(app.fiberManager.loopController());
87 
88  loopController.loop(std::move(loop));
89 
90  return 0;
91 }
size_t maxOutstanding
FiberManager fiberManager
int main()
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
STL namespace.
Single-threaded task execution engine.
std::queue< Promise< int > > pendingRequests
LoopController & loopController()
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&...args)
Definition: Memory.h:259
void loop(int iters)
uint64_t value(const typename LockFreeRingBuffer< T, Atom >::Cursor &rbcursor)
FirstArgOf< F >::type::value_type await(F &&func)