Allow folly to compile cleanly with most of the rest of MSVC's sign mismatch warnings
[folly.git] / folly / fibers / Semaphore.h
1 /*
2  * Copyright 2016 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 #pragma once
17
18 #include <folly/Synchronized.h>
19 #include <folly/fibers/Baton.h>
20
21 namespace folly {
22 namespace fibers {
23
24 /*
25  * Fiber-compatible semaphore. Will safely block fibers that wait when no
26  * tokens are available and wake fibers when signalled.
27  */
28 class Semaphore {
29  public:
30   explicit Semaphore(size_t tokenCount)
31       : capacity_(tokenCount), tokens_(int64_t(capacity_)) {}
32
33   Semaphore(const Semaphore&) = delete;
34   Semaphore(Semaphore&&) = delete;
35   Semaphore& operator=(const Semaphore&) = delete;
36   Semaphore& operator=(Semaphore&&) = delete;
37
38   /*
39    * Release a token in the semaphore. Signal the waiter if necessary.
40    */
41   void signal();
42
43   /*
44    * Wait for capacity in the semaphore.
45    */
46   void wait();
47
48   size_t getCapacity() const;
49
50  private:
51   bool waitSlow();
52   bool signalSlow();
53
54   size_t capacity_;
55   // Atomic counter
56   std::atomic<int64_t> tokens_;
57   folly::Synchronized<std::queue<folly::fibers::Baton*>> waitList_;
58 };
59
60 } // namespace fibers
61 } // namespace folly