MongoDB  2.5.0
synchronization.h
1 // synchronization.h
2 
3 /* Copyright 2010 10gen Inc.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #pragma once
19 
20 #include <boost/thread/condition.hpp>
21 #include "mutex.h"
22 
23 namespace mongo {
24 
25  /*
26  * A class to establish a synchronization point between two threads. One thread is the waiter and one is
27  * the notifier. After the notification event, both proceed normally.
28  *
29  * This class is thread-safe.
30  */
31  class Notification : boost::noncopyable {
32  public:
33  Notification();
34 
35  /*
36  * Blocks until the method 'notifyOne()' is called.
37  */
38  void waitToBeNotified();
39 
40  /*
41  * Blocks until the method 'notifyOne()' is called or the time interval elapses.
42  * Returns true if notified, false if timeout.
43  */
44  bool timedWaitToBeNotified( int millis );
45 
46  /*
47  * Notifies the waiter of '*this' that it can proceed. Can only be called once.
48  */
49  void notifyOne();
50 
51  private:
52  mongo::mutex _mutex; // protects state below
53  unsigned long long lookFor;
54  unsigned long long cur;
55  boost::condition _condition; // cond over _notified being true
56  };
57 
61  class NotifyAll : boost::noncopyable {
62  public:
63  NotifyAll();
64 
65  typedef unsigned long long When;
66 
67  When now();
68 
72  void waitFor(When);
73 
75  void awaitBeyondNow();
76 
78  void notifyAll(When);
79 
81  unsigned nWaiting() const { return _nWaiting; }
82 
83  private:
84  mongo::mutex _mutex;
85  boost::condition _condition;
86  When _lastDone;
87  When _lastReturned;
88  unsigned _nWaiting;
89  };
90 
91 } // namespace mongo