blob: c89624a12957f6737f9b9a44a1afbae79702a33a [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// 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.commitd7cae122008-07-26 21:49:384
5// Multi-threaded tests of ConditionVariable class.
6
7#include <time.h>
8#include <algorithm>
9#include <vector>
10
initial.commitd7cae122008-07-26 21:49:3811#include "base/condition_variable.h"
12#include "base/logging.h"
[email protected]6e683db2008-08-28 01:17:0213#include "base/platform_test.h"
[email protected]4f7ce3e832008-08-22 21:49:0514#include "base/platform_thread.h"
initial.commitd7cae122008-07-26 21:49:3815#include "base/scoped_ptr.h"
16#include "base/spin_wait.h"
17#include "testing/gtest/include/gtest/gtest.h"
18
19namespace {
20//------------------------------------------------------------------------------
21// Define our test class, with several common variables.
22//------------------------------------------------------------------------------
23
[email protected]6e683db2008-08-28 01:17:0224class ConditionVariableTest : public PlatformTest {
initial.commitd7cae122008-07-26 21:49:3825 public:
26 const TimeDelta kZeroMs;
27 const TimeDelta kTenMs;
28 const TimeDelta kThirtyMs;
29 const TimeDelta kFortyFiveMs;
30 const TimeDelta kSixtyMs;
31 const TimeDelta kOneHundredMs;
32
33 explicit ConditionVariableTest()
34 : kZeroMs(TimeDelta::FromMilliseconds(0)),
35 kTenMs(TimeDelta::FromMilliseconds(10)),
36 kThirtyMs(TimeDelta::FromMilliseconds(30)),
37 kFortyFiveMs(TimeDelta::FromMilliseconds(45)),
38 kSixtyMs(TimeDelta::FromMilliseconds(60)),
39 kOneHundredMs(TimeDelta::FromMilliseconds(100)) {
40 }
41};
42
43//------------------------------------------------------------------------------
44// Define a class that will control activities an several multi-threaded tests.
45// The general structure of multi-threaded tests is that a test case will
46// construct an instance of a WorkQueue. The WorkQueue will spin up some
[email protected]d324ab332008-08-18 16:00:3847// threads and control them throughout their lifetime, as well as maintaining
48// a central repository of the work thread's activity. Finally, the WorkQueue
initial.commitd7cae122008-07-26 21:49:3849// will command the the worker threads to terminate. At that point, the test
50// cases will validate that the WorkQueue has records showing that the desired
51// activities were performed.
52//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:3853
54// Callers are responsible for synchronizing access to the following class.
55// The WorkQueue::lock_, as accessed via WorkQueue::lock(), should be used for
56// all synchronized access.
[email protected]4f7ce3e832008-08-22 21:49:0557class WorkQueue : public PlatformThread::Delegate {
initial.commitd7cae122008-07-26 21:49:3858 public:
59 explicit WorkQueue(int thread_count);
60 ~WorkQueue();
61
[email protected]4f7ce3e832008-08-22 21:49:0562 // PlatformThread::Delegate interface.
63 void ThreadMain();
64
initial.commitd7cae122008-07-26 21:49:3865 //----------------------------------------------------------------------------
66 // Worker threads only call the following methods.
67 // They should use the lock to get exclusive access.
68 int GetThreadId(); // Get an ID assigned to a thread..
69 bool EveryIdWasAllocated() const; // Indicates that all IDs were handed out.
70 TimeDelta GetAnAssignment(int thread_id); // Get a work task duration.
71 void WorkIsCompleted(int thread_id);
72
73 int task_count() const;
74 bool allow_help_requests() const; // Workers can signal more workers.
75 bool shutdown() const; // Check if shutdown has been requested.
76 int shutdown_task_count() const;
77
78 void thread_shutting_down();
79 Lock* lock();
80
81 ConditionVariable* work_is_available();
82 ConditionVariable* all_threads_have_ids();
83 ConditionVariable* no_more_tasks();
84
85 //----------------------------------------------------------------------------
86 // The rest of the methods are for use by the controlling master thread (the
87 // test case code).
88 void ResetHistory();
89 int GetMinCompletionsByWorkerThread() const;
90 int GetMaxCompletionsByWorkerThread() const;
91 int GetNumThreadsTakingAssignments() const;
92 int GetNumThreadsCompletingTasks() const;
93 int GetNumberOfCompletedTasks() const;
94
95 void SetWorkTime(TimeDelta delay);
96 void SetTaskCount(int count);
97 void SetAllowHelp(bool allow);
98
99 void SetShutdown();
100
101 private:
102 // Both worker threads and controller use the following to synchronize.
103 Lock lock_;
104 ConditionVariable work_is_available_; // To tell threads there is work.
105
106 // Conditions to notify the controlling process (if it is interested).
107 ConditionVariable all_threads_have_ids_; // All threads are running.
108 ConditionVariable no_more_tasks_; // Task count is zero.
109
110 const int thread_count_;
[email protected]4f7ce3e832008-08-22 21:49:05111 scoped_array<PlatformThreadHandle> thread_handles_;
initial.commitd7cae122008-07-26 21:49:38112 std::vector<int> assignment_history_; // Number of assignment per worker.
113 std::vector<int> completion_history_; // Number of completions per worker.
114 int thread_started_counter_; // Used to issue unique id to workers.
115 int shutdown_task_count_; // Number of tasks told to shutdown
116 int task_count_; // Number of assignment tasks waiting to be processed.
117 TimeDelta worker_delay_; // Time each task takes to complete.
118 bool allow_help_requests_; // Workers can signal more workers.
119 bool shutdown_; // Set when threads need to terminate.
120};
121
122//------------------------------------------------------------------------------
initial.commitd7cae122008-07-26 21:49:38123// The next section contains the actual tests.
124//------------------------------------------------------------------------------
125
126TEST_F(ConditionVariableTest, StartupShutdownTest) {
127 Lock lock;
128
129 // First try trivial startup/shutdown.
130 {
131 ConditionVariable cv1(&lock);
132 } // Call for cv1 destruction.
133
134 // Exercise with at least a few waits.
135 ConditionVariable cv(&lock);
136
137 lock.Acquire();
138 cv.TimedWait(kTenMs); // Wait for 10 ms.
139 cv.TimedWait(kTenMs); // Wait for 10 ms.
140 lock.Release();
141
142 lock.Acquire();
143 cv.TimedWait(kTenMs); // Wait for 10 ms.
144 cv.TimedWait(kTenMs); // Wait for 10 ms.
145 cv.TimedWait(kTenMs); // Wait for 10 ms.
146 lock.Release();
147} // Call for cv destruction.
148
initial.commitd7cae122008-07-26 21:49:38149TEST_F(ConditionVariableTest, TimeoutTest) {
150 Lock lock;
151 ConditionVariable cv(&lock);
152 lock.Acquire();
153
154 TimeTicks start = TimeTicks::Now();
155 const TimeDelta WAIT_TIME = TimeDelta::FromMilliseconds(300);
156 // Allow for clocking rate granularity.
157 const TimeDelta FUDGE_TIME = TimeDelta::FromMilliseconds(50);
158
159 cv.TimedWait(WAIT_TIME + FUDGE_TIME);
160 TimeDelta duration = TimeTicks::Now() - start;
161 // We can't use EXPECT_GE here as the TimeDelta class does not support the
162 // required stream conversion.
163 EXPECT_TRUE(duration >= WAIT_TIME);
164
165 lock.Release();
166}
167
168TEST_F(ConditionVariableTest, MultiThreadConsumerTest) {
169 const int kThreadCount = 10;
170 WorkQueue queue(kThreadCount); // Start the threads.
171
172 Lock private_lock; // Used locally for master to wait.
173 AutoLock private_held_lock(private_lock);
174 ConditionVariable private_cv(&private_lock);
175
176 {
177 AutoLock auto_lock(*queue.lock());
178 while (!queue.EveryIdWasAllocated())
179 queue.all_threads_have_ids()->Wait();
180 }
181
182 // Wait a bit more to allow threads to reach their wait state.
183 private_cv.TimedWait(kTenMs);
184
185 {
186 // Since we have no tasks, all threads should be waiting by now.
187 AutoLock auto_lock(*queue.lock());
188 EXPECT_EQ(0, queue.GetNumThreadsTakingAssignments());
189 EXPECT_EQ(0, queue.GetNumThreadsCompletingTasks());
190 EXPECT_EQ(0, queue.task_count());
191 EXPECT_EQ(0, queue.GetMaxCompletionsByWorkerThread());
192 EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
193 EXPECT_EQ(0, queue.GetNumberOfCompletedTasks());
194
195 // Set up to make one worker do 3 30ms tasks.
196 queue.ResetHistory();
197 queue.SetTaskCount(3);
198 queue.SetWorkTime(kThirtyMs);
199 queue.SetAllowHelp(false);
200 }
201 queue.work_is_available()->Signal(); // Start up one thread.
202 // Wait to allow solo worker insufficient time to get done.
203 private_cv.TimedWait(kFortyFiveMs); // Should take about 90 ms.
204
205 {
206 // Check that all work HASN'T completed yet.
207 AutoLock auto_lock(*queue.lock());
208 EXPECT_EQ(1, queue.GetNumThreadsTakingAssignments());
209 EXPECT_EQ(1, queue.GetNumThreadsCompletingTasks());
210 EXPECT_GT(2, queue.task_count()); // 2 should have started.
211 EXPECT_GT(3, queue.GetMaxCompletionsByWorkerThread());
212 EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
213 EXPECT_EQ(1, queue.GetNumberOfCompletedTasks());
214 }
215 // Wait to allow solo workers to get done.
216 private_cv.TimedWait(kSixtyMs); // Should take about 45ms more.
217
218 {
219 // Check that all work was done by one thread id.
220 AutoLock auto_lock(*queue.lock());
221 EXPECT_EQ(1, queue.GetNumThreadsTakingAssignments());
222 EXPECT_EQ(1, queue.GetNumThreadsCompletingTasks());
223 EXPECT_EQ(0, queue.task_count());
224 EXPECT_EQ(3, queue.GetMaxCompletionsByWorkerThread());
225 EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
226 EXPECT_EQ(3, queue.GetNumberOfCompletedTasks());
227
228 // Set up to make each task include getting help from another worker.
229 queue.ResetHistory();
230 queue.SetTaskCount(3);
231 queue.SetWorkTime(kThirtyMs);
232 queue.SetAllowHelp(true);
233 }
234 queue.work_is_available()->Signal(); // But each worker can signal another.
235 // Wait to allow the 3 workers to get done.
236 private_cv.TimedWait(kFortyFiveMs); // Should take about 30 ms.
237
238 {
239 AutoLock auto_lock(*queue.lock());
240 EXPECT_EQ(3, queue.GetNumThreadsTakingAssignments());
241 EXPECT_EQ(3, queue.GetNumThreadsCompletingTasks());
242 EXPECT_EQ(0, queue.task_count());
243 EXPECT_EQ(1, queue.GetMaxCompletionsByWorkerThread());
244 EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
245 EXPECT_EQ(3, queue.GetNumberOfCompletedTasks());
246
247 // Try to ask all workers to help, and only a few will do the work.
248 queue.ResetHistory();
249 queue.SetTaskCount(3);
250 queue.SetWorkTime(kThirtyMs);
251 queue.SetAllowHelp(false);
252 }
253 queue.work_is_available()->Broadcast(); // Make them all try.
254 // Wait to allow the 3 workers to get done.
255 private_cv.TimedWait(kFortyFiveMs);
256
257 {
258 AutoLock auto_lock(*queue.lock());
259 EXPECT_EQ(3, queue.GetNumThreadsTakingAssignments());
260 EXPECT_EQ(3, queue.GetNumThreadsCompletingTasks());
261 EXPECT_EQ(0, queue.task_count());
262 EXPECT_EQ(1, queue.GetMaxCompletionsByWorkerThread());
263 EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
264 EXPECT_EQ(3, queue.GetNumberOfCompletedTasks());
265
266 // Set up to make each task get help from another worker.
267 queue.ResetHistory();
268 queue.SetTaskCount(3);
269 queue.SetWorkTime(kThirtyMs);
270 queue.SetAllowHelp(true); // Allow (unnecessary) help requests.
271 }
272 queue.work_is_available()->Broadcast(); // We already signal all threads.
273 // Wait to allow the 3 workers to get done.
274 private_cv.TimedWait(kOneHundredMs);
275
276 {
277 AutoLock auto_lock(*queue.lock());
278 EXPECT_EQ(3, queue.GetNumThreadsTakingAssignments());
279 EXPECT_EQ(3, queue.GetNumThreadsCompletingTasks());
280 EXPECT_EQ(0, queue.task_count());
281 EXPECT_EQ(1, queue.GetMaxCompletionsByWorkerThread());
282 EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
283 EXPECT_EQ(3, queue.GetNumberOfCompletedTasks());
284
285 // Set up to make each task get help from another worker.
286 queue.ResetHistory();
287 queue.SetTaskCount(20);
288 queue.SetWorkTime(kThirtyMs);
289 queue.SetAllowHelp(true);
290 }
291 queue.work_is_available()->Signal(); // But each worker can signal another.
292 // Wait to allow the 10 workers to get done.
293 private_cv.TimedWait(kOneHundredMs); // Should take about 60 ms.
294
295 {
296 AutoLock auto_lock(*queue.lock());
297 EXPECT_EQ(10, queue.GetNumThreadsTakingAssignments());
298 EXPECT_EQ(10, queue.GetNumThreadsCompletingTasks());
299 EXPECT_EQ(0, queue.task_count());
300 EXPECT_EQ(2, queue.GetMaxCompletionsByWorkerThread());
301 EXPECT_EQ(2, queue.GetMinCompletionsByWorkerThread());
302 EXPECT_EQ(20, queue.GetNumberOfCompletedTasks());
303
304 // Same as last test, but with Broadcast().
305 queue.ResetHistory();
306 queue.SetTaskCount(20); // 2 tasks per process.
307 queue.SetWorkTime(kThirtyMs);
308 queue.SetAllowHelp(true);
309 }
310 queue.work_is_available()->Broadcast();
311 // Wait to allow the 10 workers to get done.
312 private_cv.TimedWait(kOneHundredMs); // Should take about 60 ms.
313
314 {
315 AutoLock auto_lock(*queue.lock());
316 EXPECT_EQ(10, queue.GetNumThreadsTakingAssignments());
317 EXPECT_EQ(10, queue.GetNumThreadsCompletingTasks());
318 EXPECT_EQ(0, queue.task_count());
319 EXPECT_EQ(2, queue.GetMaxCompletionsByWorkerThread());
320 EXPECT_EQ(2, queue.GetMinCompletionsByWorkerThread());
321 EXPECT_EQ(20, queue.GetNumberOfCompletedTasks());
322
323 queue.SetShutdown();
324 }
325 queue.work_is_available()->Broadcast(); // Force check for shutdown.
326
327 SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(1),
328 queue.shutdown_task_count() == kThreadCount);
[email protected]4f7ce3e832008-08-22 21:49:05329 PlatformThread::Sleep(10); // Be sure they're all shutdown.
initial.commitd7cae122008-07-26 21:49:38330}
331
332TEST_F(ConditionVariableTest, LargeFastTaskTest) {
333 const int kThreadCount = 200;
334 WorkQueue queue(kThreadCount); // Start the threads.
335
336 Lock private_lock; // Used locally for master to wait.
337 AutoLock private_held_lock(private_lock);
338 ConditionVariable private_cv(&private_lock);
339
340 {
341 AutoLock auto_lock(*queue.lock());
342 while (!queue.EveryIdWasAllocated())
343 queue.all_threads_have_ids()->Wait();
344 }
345
346 // Wait a bit more to allow threads to reach their wait state.
347 private_cv.TimedWait(kThirtyMs);
348
349 {
350 // Since we have no tasks, all threads should be waiting by now.
351 AutoLock auto_lock(*queue.lock());
352 EXPECT_EQ(0, queue.GetNumThreadsTakingAssignments());
353 EXPECT_EQ(0, queue.GetNumThreadsCompletingTasks());
354 EXPECT_EQ(0, queue.task_count());
355 EXPECT_EQ(0, queue.GetMaxCompletionsByWorkerThread());
356 EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
357 EXPECT_EQ(0, queue.GetNumberOfCompletedTasks());
358
359 // Set up to make all workers do (an average of) 20 tasks.
360 queue.ResetHistory();
361 queue.SetTaskCount(20 * kThreadCount);
362 queue.SetWorkTime(kFortyFiveMs);
363 queue.SetAllowHelp(false);
364 }
365 queue.work_is_available()->Broadcast(); // Start up all threads.
366 // Wait until we've handed out all tasks.
367 {
368 AutoLock auto_lock(*queue.lock());
369 while (queue.task_count() != 0)
370 queue.no_more_tasks()->Wait();
371 }
372
373 // Wait till the last of the tasks complete.
374 // Don't bother to use locks: We may not get info in time... but we'll see it
375 // eventually.
376 SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(1),
377 20 * kThreadCount ==
378 queue.GetNumberOfCompletedTasks());
379
380 {
381 // With Broadcast(), every thread should have participated.
382 // but with racing.. they may not all have done equal numbers of tasks.
383 AutoLock auto_lock(*queue.lock());
384 EXPECT_EQ(kThreadCount, queue.GetNumThreadsTakingAssignments());
385 EXPECT_EQ(kThreadCount, queue.GetNumThreadsCompletingTasks());
386 EXPECT_EQ(0, queue.task_count());
387 EXPECT_LE(20, queue.GetMaxCompletionsByWorkerThread());
388 EXPECT_EQ(20 * kThreadCount, queue.GetNumberOfCompletedTasks());
389
390 // Set up to make all workers do (an average of) 4 tasks.
391 queue.ResetHistory();
392 queue.SetTaskCount(kThreadCount * 4);
393 queue.SetWorkTime(kFortyFiveMs);
394 queue.SetAllowHelp(true); // Might outperform Broadcast().
395 }
396 queue.work_is_available()->Signal(); // Start up one thread.
397
398 // Wait until we've handed out all tasks
399 {
400 AutoLock auto_lock(*queue.lock());
401 while (queue.task_count() != 0)
402 queue.no_more_tasks()->Wait();
403 }
404
405 // Wait till the last of the tasks complete.
406 // Don't bother to use locks: We may not get info in time... but we'll see it
407 // eventually.
408 SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(1),
409 4 * kThreadCount ==
410 queue.GetNumberOfCompletedTasks());
411
412 {
413 // With Signal(), every thread should have participated.
414 // but with racing.. they may not all have done four tasks.
415 AutoLock auto_lock(*queue.lock());
416 EXPECT_EQ(kThreadCount, queue.GetNumThreadsTakingAssignments());
417 EXPECT_EQ(kThreadCount, queue.GetNumThreadsCompletingTasks());
418 EXPECT_EQ(0, queue.task_count());
419 EXPECT_LE(4, queue.GetMaxCompletionsByWorkerThread());
420 EXPECT_EQ(4 * kThreadCount, queue.GetNumberOfCompletedTasks());
421
422 queue.SetShutdown();
423 }
424 queue.work_is_available()->Broadcast(); // Force check for shutdown.
425
[email protected]d324ab332008-08-18 16:00:38426 // Wait for shutdowns to complete.
initial.commitd7cae122008-07-26 21:49:38427 SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(1),
428 queue.shutdown_task_count() == kThreadCount);
[email protected]4f7ce3e832008-08-22 21:49:05429 PlatformThread::Sleep(10); // Be sure they're all shutdown.
initial.commitd7cae122008-07-26 21:49:38430}
431
432//------------------------------------------------------------------------------
433// Finally we provide the implementation for the methods in the WorkQueue class.
434//------------------------------------------------------------------------------
435
436WorkQueue::WorkQueue(int thread_count)
437 : lock_(),
438 work_is_available_(&lock_),
439 all_threads_have_ids_(&lock_),
440 no_more_tasks_(&lock_),
441 thread_count_(thread_count),
[email protected]4f7ce3e832008-08-22 21:49:05442 thread_handles_(new PlatformThreadHandle[thread_count]),
initial.commitd7cae122008-07-26 21:49:38443 assignment_history_(thread_count),
444 completion_history_(thread_count),
445 thread_started_counter_(0),
446 shutdown_task_count_(0),
447 task_count_(0),
448 allow_help_requests_(false),
449 shutdown_(false) {
450 EXPECT_GE(thread_count_, 1);
451 ResetHistory();
452 SetTaskCount(0);
453 SetWorkTime(TimeDelta::FromMilliseconds(30));
454
455 for (int i = 0; i < thread_count_; ++i) {
[email protected]4f7ce3e832008-08-22 21:49:05456 PlatformThreadHandle pth;
457 EXPECT_TRUE(PlatformThread::Create(0, this, &pth));
458 thread_handles_[i] = pth;
initial.commitd7cae122008-07-26 21:49:38459 }
460}
461
462WorkQueue::~WorkQueue() {
463 {
464 AutoLock auto_lock(lock_);
465 SetShutdown();
466 }
467 work_is_available_.Broadcast(); // Tell them all to terminate.
initial.commitd7cae122008-07-26 21:49:38468
469 for (int i = 0; i < thread_count_; ++i) {
[email protected]4f7ce3e832008-08-22 21:49:05470 PlatformThread::Join(thread_handles_[i]);
initial.commitd7cae122008-07-26 21:49:38471 }
472}
473
474int WorkQueue::GetThreadId() {
475 DCHECK(!EveryIdWasAllocated());
476 return thread_started_counter_++; // Give out Unique IDs.
477}
478
479bool WorkQueue::EveryIdWasAllocated() const {
480 return thread_count_ == thread_started_counter_;
481}
482
483TimeDelta WorkQueue::GetAnAssignment(int thread_id) {
484 DCHECK_LT(0, task_count_);
485 assignment_history_[thread_id]++;
486 if (0 == --task_count_) {
487 no_more_tasks_.Signal();
488 }
489 return worker_delay_;
490}
491
492void WorkQueue::WorkIsCompleted(int thread_id) {
493 completion_history_[thread_id]++;
494}
495
496int WorkQueue::task_count() const {
497 return task_count_;
498}
499
500bool WorkQueue::allow_help_requests() const {
501 return allow_help_requests_;
502}
503
504bool WorkQueue::shutdown() const {
505 return shutdown_;
506}
507
508int WorkQueue::shutdown_task_count() const {
509 return shutdown_task_count_;
510}
511
512void WorkQueue::thread_shutting_down() {
513 shutdown_task_count_++;
514}
515
516Lock* WorkQueue::lock() {
517 return &lock_;
518}
519
520ConditionVariable* WorkQueue::work_is_available() {
521 return &work_is_available_;
522}
523
524ConditionVariable* WorkQueue::all_threads_have_ids() {
525 return &all_threads_have_ids_;
526}
527
528ConditionVariable* WorkQueue::no_more_tasks() {
529 return &no_more_tasks_;
530}
531
532void WorkQueue::ResetHistory() {
533 for (int i = 0; i < thread_count_; ++i) {
534 assignment_history_[i] = 0;
535 completion_history_[i] = 0;
536 }
537}
538
539int WorkQueue::GetMinCompletionsByWorkerThread() const {
540 int minumum = completion_history_[0];
541 for (int i = 0; i < thread_count_; ++i)
542 minumum = std::min(minumum, completion_history_[i]);
543 return minumum;
544}
545
546int WorkQueue::GetMaxCompletionsByWorkerThread() const {
547 int maximum = completion_history_[0];
548 for (int i = 0; i < thread_count_; ++i)
549 maximum = std::max(maximum, completion_history_[i]);
550 return maximum;
551}
552
553int WorkQueue::GetNumThreadsTakingAssignments() const {
554 int count = 0;
555 for (int i = 0; i < thread_count_; ++i)
556 if (assignment_history_[i])
557 count++;
558 return count;
559}
560
561int WorkQueue::GetNumThreadsCompletingTasks() const {
562 int count = 0;
563 for (int i = 0; i < thread_count_; ++i)
564 if (completion_history_[i])
565 count++;
566 return count;
567}
568
569int WorkQueue::GetNumberOfCompletedTasks() const {
570 int total = 0;
571 for (int i = 0; i < thread_count_; ++i)
572 total += completion_history_[i];
573 return total;
574}
575
576void WorkQueue::SetWorkTime(TimeDelta delay) {
577 worker_delay_ = delay;
578}
579
580void WorkQueue::SetTaskCount(int count) {
581 task_count_ = count;
582}
583
584void WorkQueue::SetAllowHelp(bool allow) {
585 allow_help_requests_ = allow;
586}
587
588void WorkQueue::SetShutdown() {
589 shutdown_ = true;
590}
591
[email protected]4f7ce3e832008-08-22 21:49:05592//------------------------------------------------------------------------------
593// Define the standard worker task. Several tests will spin out many of these
594// threads.
595//------------------------------------------------------------------------------
596
597// The multithread tests involve several threads with a task to perform as
598// directed by an instance of the class WorkQueue.
599// The task is to:
600// a) Check to see if there are more tasks (there is a task counter).
601// a1) Wait on condition variable if there are no tasks currently.
602// b) Call a function to see what should be done.
603// c) Do some computation based on the number of milliseconds returned in (b).
604// d) go back to (a).
605
606// WorkQueue::ThreadMain() implements the above task for all threads.
607// It calls the controlling object to tell the creator about progress, and to
608// ask about tasks.
609
610void WorkQueue::ThreadMain() {
611 int thread_id;
612 {
613 AutoLock auto_lock(lock_);
614 thread_id = GetThreadId();
615 if (EveryIdWasAllocated())
616 all_threads_have_ids()->Signal(); // Tell creator we're ready.
617 }
618
619 Lock private_lock; // Used to waste time on "our work".
620 while (1) { // This is the main consumer loop.
621 TimeDelta work_time;
622 bool could_use_help;
623 {
624 AutoLock auto_lock(lock_);
625 while (0 == task_count() && !shutdown()) {
626 work_is_available()->Wait();
627 }
628 if (shutdown()) {
629 // Ack the notification of a shutdown message back to the controller.
630 thread_shutting_down();
631 return; // Terminate.
632 }
633 // Get our task duration from the queue.
634 work_time = GetAnAssignment(thread_id);
635 could_use_help = (task_count() > 0) && allow_help_requests();
636 } // Release lock
637
638 // Do work (outside of locked region.
639 if (could_use_help)
640 work_is_available()->Signal(); // Get help from other threads.
641
642 if (work_time > TimeDelta::FromMilliseconds(0)) {
643 // We could just sleep(), but we'll instead further exercise the
644 // condition variable class, and do a timed wait.
645 AutoLock auto_lock(private_lock);
646 ConditionVariable private_cv(&private_lock);
647 private_cv.TimedWait(work_time); // Unsynchronized waiting.
648 }
649
650 {
651 AutoLock auto_lock(lock_);
652 // Send notification that we completed our "work."
653 WorkIsCompleted(thread_id);
654 }
655 }
656}
657
initial.commitd7cae122008-07-26 21:49:38658} // namespace
license.botbf09a502008-08-24 00:55:55659