(wangle) Use an atomic_flag to make FutureObject threadsafe
[folly.git] / folly / wangle / ManualExecutor.h
1 /*
2  * Copyright 2014 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 #pragma once
18 #include "folly/wangle/Executor.h"
19 #include <semaphore.h>
20 #include <memory>
21 #include <mutex>
22 #include <queue>
23
24 namespace folly { namespace wangle {
25
26   class ManualExecutor : public Executor {
27    public:
28     ManualExecutor();
29
30     void add(std::function<void()>&&) override;
31
32     /// Do work. Returns the number of runnables that were executed (maybe 0).
33     /// Non-blocking.
34     size_t run();
35
36     /// Wait for work to do.
37     void wait();
38
39     /// Wait for work to do, and do it.
40     void makeProgress() {
41       wait();
42       run();
43     }
44
45    private:
46     std::mutex lock_;
47     std::queue<std::function<void()>> runnables_;
48     sem_t sem_;
49   };
50
51 }}