1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #ifndef _THRIFT_CONCURRENCY_MUTEX_H_
21 #define _THRIFT_CONCURRENCY_MUTEX_H_ 1
22 
23 #include <memory>
24 #include <thrift/TNonCopyable.h>
25 
26 namespace apache {
27 namespace thrift {
28 namespace concurrency {
29 
30 /**
31  * NOTE: All mutex implementations throw an exception on failure.  See each
32  *       specific implementation to understand the exception type(s) used.
33  */
34 
35 /**
36  * A simple mutex class
37  *
38  * @version $Id:$
39  */
40 class Mutex {
41 public:
42   Mutex();
43   virtual ~Mutex() = default;
44 
45   virtual void lock() const;
46   virtual bool trylock() const;
47   virtual bool timedlock(int64_t milliseconds) const;
48   virtual void unlock() const;
49 
50   void* getUnderlyingImpl() const;
51 
52 private:
53   class impl;
54   std::shared_ptr<impl> impl_;
55 };
56 
57 
58 class Guard : apache::thrift::TNonCopyable {
59 public:
60   Guard(const Mutex& value, int64_t timeout = 0) : mutex_(&value) {
61     if (timeout == 0) {
62       value.lock();
63     } else if (timeout < 0) {
64       if (!value.trylock()) {
65         mutex_ = nullptr;
66       }
67     } else {
68       if (!value.timedlock(timeout)) {
69         mutex_ = nullptr;
70       }
71     }
72   }
~Guard()73   ~Guard() {
74     if (mutex_) {
75       mutex_->unlock();
76     }
77   }
78 
79   operator bool() const { return (mutex_ != nullptr); }
80 
81 private:
82   const Mutex* mutex_;
83 };
84 
85 }
86 }
87 } // apache::thrift::concurrency
88 
89 #endif // #ifndef _THRIFT_CONCURRENCY_MUTEX_H_
90