blob: 9307d8ce401a4192f1e68f867c8146e50c1a8e91 [file] [log] [blame]
license.botf003cfe2008-08-24 09:55:55 +09001// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit3f4a7322008-07-27 06:49:38 +09004
mmentovai@google.comf5a40002008-08-09 01:19:43 +09005// ConditionVariable wraps pthreads condition variable synchronization or, on
6// Windows, simulates it. This functionality is very helpful for having
7// several threads wait for an event, as is common with a thread pool managed
8// by a master. The meaning of such an event in the (worker) thread pool
9// scenario is that additional tasks are now available for processing. It is
10// used in Chrome in the DNS prefetching system to notify worker threads that
11// a queue now has items (tasks) which need to be tended to. A related use
12// would have a pool manager waiting on a ConditionVariable, waiting for a
13// thread in the pool to announce (signal) that there is now more room in a
14// (bounded size) communications queue for the manager to deposit tasks, or,
15// as a second example, that the queue of tasks is completely empty and all
16// workers are waiting.
17//
initial.commit3f4a7322008-07-27 06:49:38 +090018// USAGE NOTE 1: spurious signal events are possible with this and
19// most implementations of condition variables. As a result, be
20// *sure* to retest your condition before proceeding. The following
21// is a good example of doing this correctly:
mmentovai@google.comf5a40002008-08-09 01:19:43 +090022//
initial.commit3f4a7322008-07-27 06:49:38 +090023// while (!work_to_be_done()) Wait(...);
mmentovai@google.comf5a40002008-08-09 01:19:43 +090024//
initial.commit3f4a7322008-07-27 06:49:38 +090025// In contrast do NOT do the following:
mmentovai@google.comf5a40002008-08-09 01:19:43 +090026//
initial.commit3f4a7322008-07-27 06:49:38 +090027// if (!work_to_be_done()) Wait(...); // Don't do this.
mmentovai@google.comf5a40002008-08-09 01:19:43 +090028//
initial.commit3f4a7322008-07-27 06:49:38 +090029// Especially avoid the above if you are relying on some other thread only
30// issuing a signal up *if* there is work-to-do. There can/will
31// be spurious signals. Recheck state on waiting thread before
32// assuming the signal was intentional. Caveat caller ;-).
mmentovai@google.comf5a40002008-08-09 01:19:43 +090033//
initial.commit3f4a7322008-07-27 06:49:38 +090034// USAGE NOTE 2: Broadcast() frees up all waiting threads at once,
35// which leads to contention for the locks they all held when they
36// called Wait(). This results in POOR performance. A much better
37// approach to getting a lot of threads out of Wait() is to have each
38// thread (upon exiting Wait()) call Signal() to free up another
39// Wait'ing thread. Look at condition_variable_unittest.cc for
40// both examples.
mmentovai@google.comf5a40002008-08-09 01:19:43 +090041//
initial.commit3f4a7322008-07-27 06:49:38 +090042// Broadcast() can be used nicely during teardown, as it gets the job
43// done, and leaves no sleeping threads... and performance is less
44// critical at that point.
mmentovai@google.comf5a40002008-08-09 01:19:43 +090045//
initial.commit3f4a7322008-07-27 06:49:38 +090046// The semantics of Broadcast() are carefully crafted so that *all*
47// threads that were waiting when the request was made will indeed
48// get signaled. Some implementations mess up, and don't signal them
49// all, while others allow the wait to be effectively turned off (for
ericroman@google.comdbff4f52008-08-19 01:00:38 +090050// a while while waiting threads come around). This implementation
initial.commit3f4a7322008-07-27 06:49:38 +090051// appears correct, as it will not "lose" any signals, and will guarantee
52// that all threads get signaled by Broadcast().
mmentovai@google.comf5a40002008-08-09 01:19:43 +090053//
initial.commit3f4a7322008-07-27 06:49:38 +090054// This implementation offers support for "performance" in its selection of
55// which thread to revive. Performance, in direct contrast with "fairness,"
56// assures that the thread that most recently began to Wait() is selected by
57// Signal to revive. Fairness would (if publicly supported) assure that the
58// thread that has Wait()ed the longest is selected. The default policy
59// may improve performance, as the selected thread may have a greater chance of
60// having some of its stack data in various CPU caches.
mmentovai@google.comf5a40002008-08-09 01:19:43 +090061//
initial.commit3f4a7322008-07-27 06:49:38 +090062// For a discussion of the many very subtle implementation details, see the FAQ
mmentovai@google.comf5a40002008-08-09 01:19:43 +090063// at the end of condition_variable_win.cc.
initial.commit3f4a7322008-07-27 06:49:38 +090064
mmentovai@google.comf5a40002008-08-09 01:19:43 +090065#ifndef BASE_CONDITION_VARIABLE_H_
66#define BASE_CONDITION_VARIABLE_H_
initial.commit3f4a7322008-07-27 06:49:38 +090067
68#include "base/lock.h"
69#include "base/logging.h"
70#include "base/scoped_ptr.h"
71#include "base/time.h"
72
initial.commit3f4a7322008-07-27 06:49:38 +090073class ConditionVariable {
74 public:
75 // Construct a cv for use with ONLY one user lock.
76 explicit ConditionVariable(Lock* user_lock);
77
78 ~ConditionVariable();
79
80 // Wait() releases the caller's critical section atomically as it starts to
81 // sleep, and the reacquires it when it is signaled.
mmentovai@google.comf5a40002008-08-09 01:19:43 +090082 void Wait();
initial.commit3f4a7322008-07-27 06:49:38 +090083 void TimedWait(const TimeDelta& max_time);
initial.commit3f4a7322008-07-27 06:49:38 +090084
85 // Broadcast() revives all waiting threads.
86 void Broadcast();
87 // Signal() revives one waiting thread.
88 void Signal();
89
90 private:
mmentovai@google.comf5a40002008-08-09 01:19:43 +090091
92#if defined(OS_WIN)
93
initial.commit3f4a7322008-07-27 06:49:38 +090094 // Define Event class that is used to form circularly linked lists.
95 // The list container is an element with NULL as its handle_ value.
96 // The actual list elements have a non-zero handle_ value.
97 // All calls to methods MUST be done under protection of a lock so that links
98 // can be validated. Without the lock, some links might asynchronously
99 // change, and the assertions would fail (as would list change operations).
100 class Event {
101 public:
102 // Default constructor with no arguments creates a list container.
103 Event();
104 ~Event();
105
106 // InitListElement transitions an instance from a container, to an element.
107 void InitListElement();
108
109 // Methods for use on lists.
110 bool IsEmpty() const;
111 void PushBack(Event* other);
112 Event* PopFront();
113 Event* PopBack();
114
115 // Methods for use on list elements.
116 // Accessor method.
117 HANDLE handle() const;
118 // Pull an element from a list (if it's in one).
119 Event* Extract();
120
121 // Method for use on a list element or on a list.
122 bool IsSingleton() const;
123
124 private:
125 // Provide pre/post conditions to validate correct manipulations.
126 bool ValidateAsDistinct(Event* other) const;
127 bool ValidateAsItem() const;
128 bool ValidateAsList() const;
129 bool ValidateLinks() const;
130
131 HANDLE handle_;
132 Event* next_;
133 Event* prev_;
mmentovai@google.comf5a40002008-08-09 01:19:43 +0900134 DISALLOW_COPY_AND_ASSIGN(Event);
initial.commit3f4a7322008-07-27 06:49:38 +0900135 };
136
137 // Note that RUNNING is an unlikely number to have in RAM by accident.
138 // This helps with defensive destructor coding in the face of user error.
139 enum RunState { SHUTDOWN = 0, RUNNING = 64213 };
140
141 // Internal implementation methods supporting Wait().
142 Event* GetEventForWaiting();
143 void RecycleEvent(Event* used_event);
144
145 RunState run_state_;
146
147 // Private critical section for access to member data.
148 Lock internal_lock_;
mmentovai@google.comf5a40002008-08-09 01:19:43 +0900149
initial.commit3f4a7322008-07-27 06:49:38 +0900150 // Lock that is acquired before calling Wait().
151 Lock& user_lock_;
152
153 // Events that threads are blocked on.
154 Event waiting_list_;
155
156 // Free list for old events.
157 Event recycling_list_;
158 int recycling_list_size_;
159
160 // The number of allocated, but not yet deleted events.
161 int allocation_counter_;
162
mmentovai@google.comf5a40002008-08-09 01:19:43 +0900163#elif defined(OS_POSIX)
164
165 pthread_cond_t condition_;
166 pthread_mutex_t* user_mutex_;
167
168#endif
169
170 DISALLOW_COPY_AND_ASSIGN(ConditionVariable);
initial.commit3f4a7322008-07-27 06:49:38 +0900171};
172
mmentovai@google.comf5a40002008-08-09 01:19:43 +0900173#endif // BASE_CONDITION_VARIABLE_H_
license.botf003cfe2008-08-24 09:55:55 +0900174