Add ICU message format support
[chromium-blink-merge.git] / base / synchronization / condition_variable_unittest.cc
blobe63a723d0097813cdee76c86be6b4e797dffd6f4
1 // Copyright (c) 2012 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.
5 // Multi-threaded tests of ConditionVariable class.
7 #include <time.h>
8 #include <algorithm>
9 #include <vector>
11 #include "base/bind.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/single_thread_task_runner.h"
16 #include "base/synchronization/condition_variable.h"
17 #include "base/synchronization/lock.h"
18 #include "base/synchronization/spin_wait.h"
19 #include "base/threading/platform_thread.h"
20 #include "base/threading/thread.h"
21 #include "base/threading/thread_collision_warner.h"
22 #include "base/time/time.h"
23 #include "testing/gtest/include/gtest/gtest.h"
24 #include "testing/platform_test.h"
26 namespace base {
28 namespace {
29 //------------------------------------------------------------------------------
30 // Define our test class, with several common variables.
31 //------------------------------------------------------------------------------
33 class ConditionVariableTest : public PlatformTest {
34 public:
35 const TimeDelta kZeroMs;
36 const TimeDelta kTenMs;
37 const TimeDelta kThirtyMs;
38 const TimeDelta kFortyFiveMs;
39 const TimeDelta kSixtyMs;
40 const TimeDelta kOneHundredMs;
42 ConditionVariableTest()
43 : kZeroMs(TimeDelta::FromMilliseconds(0)),
44 kTenMs(TimeDelta::FromMilliseconds(10)),
45 kThirtyMs(TimeDelta::FromMilliseconds(30)),
46 kFortyFiveMs(TimeDelta::FromMilliseconds(45)),
47 kSixtyMs(TimeDelta::FromMilliseconds(60)),
48 kOneHundredMs(TimeDelta::FromMilliseconds(100)) {
52 //------------------------------------------------------------------------------
53 // Define a class that will control activities an several multi-threaded tests.
54 // The general structure of multi-threaded tests is that a test case will
55 // construct an instance of a WorkQueue. The WorkQueue will spin up some
56 // threads and control them throughout their lifetime, as well as maintaining
57 // a central repository of the work thread's activity. Finally, the WorkQueue
58 // will command the the worker threads to terminate. At that point, the test
59 // cases will validate that the WorkQueue has records showing that the desired
60 // activities were performed.
61 //------------------------------------------------------------------------------
63 // Callers are responsible for synchronizing access to the following class.
64 // The WorkQueue::lock_, as accessed via WorkQueue::lock(), should be used for
65 // all synchronized access.
66 class WorkQueue : public PlatformThread::Delegate {
67 public:
68 explicit WorkQueue(int thread_count);
69 ~WorkQueue() override;
71 // PlatformThread::Delegate interface.
72 void ThreadMain() override;
74 //----------------------------------------------------------------------------
75 // Worker threads only call the following methods.
76 // They should use the lock to get exclusive access.
77 int GetThreadId(); // Get an ID assigned to a thread..
78 bool EveryIdWasAllocated() const; // Indicates that all IDs were handed out.
79 TimeDelta GetAnAssignment(int thread_id); // Get a work task duration.
80 void WorkIsCompleted(int thread_id);
82 int task_count() const;
83 bool allow_help_requests() const; // Workers can signal more workers.
84 bool shutdown() const; // Check if shutdown has been requested.
86 void thread_shutting_down();
89 //----------------------------------------------------------------------------
90 // Worker threads can call them but not needed to acquire a lock.
91 Lock* lock();
93 ConditionVariable* work_is_available();
94 ConditionVariable* all_threads_have_ids();
95 ConditionVariable* no_more_tasks();
97 //----------------------------------------------------------------------------
98 // The rest of the methods are for use by the controlling master thread (the
99 // test case code).
100 void ResetHistory();
101 int GetMinCompletionsByWorkerThread() const;
102 int GetMaxCompletionsByWorkerThread() const;
103 int GetNumThreadsTakingAssignments() const;
104 int GetNumThreadsCompletingTasks() const;
105 int GetNumberOfCompletedTasks() const;
107 void SetWorkTime(TimeDelta delay);
108 void SetTaskCount(int count);
109 void SetAllowHelp(bool allow);
111 // The following must be called without locking, and will spin wait until the
112 // threads are all in a wait state.
113 void SpinUntilAllThreadsAreWaiting();
114 void SpinUntilTaskCountLessThan(int task_count);
116 // Caller must acquire lock before calling.
117 void SetShutdown();
119 // Compares the |shutdown_task_count_| to the |thread_count| and returns true
120 // if they are equal. This check will acquire the |lock_| so the caller
121 // should not hold the lock when calling this method.
122 bool ThreadSafeCheckShutdown(int thread_count);
124 private:
125 // Both worker threads and controller use the following to synchronize.
126 Lock lock_;
127 ConditionVariable work_is_available_; // To tell threads there is work.
129 // Conditions to notify the controlling process (if it is interested).
130 ConditionVariable all_threads_have_ids_; // All threads are running.
131 ConditionVariable no_more_tasks_; // Task count is zero.
133 const int thread_count_;
134 int waiting_thread_count_;
135 scoped_ptr<PlatformThreadHandle[]> thread_handles_;
136 std::vector<int> assignment_history_; // Number of assignment per worker.
137 std::vector<int> completion_history_; // Number of completions per worker.
138 int thread_started_counter_; // Used to issue unique id to workers.
139 int shutdown_task_count_; // Number of tasks told to shutdown
140 int task_count_; // Number of assignment tasks waiting to be processed.
141 TimeDelta worker_delay_; // Time each task takes to complete.
142 bool allow_help_requests_; // Workers can signal more workers.
143 bool shutdown_; // Set when threads need to terminate.
145 DFAKE_MUTEX(locked_methods_);
148 //------------------------------------------------------------------------------
149 // The next section contains the actual tests.
150 //------------------------------------------------------------------------------
152 TEST_F(ConditionVariableTest, StartupShutdownTest) {
153 Lock lock;
155 // First try trivial startup/shutdown.
157 ConditionVariable cv1(&lock);
158 } // Call for cv1 destruction.
160 // Exercise with at least a few waits.
161 ConditionVariable cv(&lock);
163 lock.Acquire();
164 cv.TimedWait(kTenMs); // Wait for 10 ms.
165 cv.TimedWait(kTenMs); // Wait for 10 ms.
166 lock.Release();
168 lock.Acquire();
169 cv.TimedWait(kTenMs); // Wait for 10 ms.
170 cv.TimedWait(kTenMs); // Wait for 10 ms.
171 cv.TimedWait(kTenMs); // Wait for 10 ms.
172 lock.Release();
173 } // Call for cv destruction.
175 TEST_F(ConditionVariableTest, TimeoutTest) {
176 Lock lock;
177 ConditionVariable cv(&lock);
178 lock.Acquire();
180 TimeTicks start = TimeTicks::Now();
181 const TimeDelta WAIT_TIME = TimeDelta::FromMilliseconds(300);
182 // Allow for clocking rate granularity.
183 const TimeDelta FUDGE_TIME = TimeDelta::FromMilliseconds(50);
185 cv.TimedWait(WAIT_TIME + FUDGE_TIME);
186 TimeDelta duration = TimeTicks::Now() - start;
187 // We can't use EXPECT_GE here as the TimeDelta class does not support the
188 // required stream conversion.
189 EXPECT_TRUE(duration >= WAIT_TIME);
191 lock.Release();
194 #if defined(OS_POSIX)
195 const int kDiscontinuitySeconds = 2;
197 void BackInTime(Lock* lock) {
198 AutoLock auto_lock(*lock);
200 timeval tv;
201 gettimeofday(&tv, NULL);
202 tv.tv_sec -= kDiscontinuitySeconds;
203 settimeofday(&tv, NULL);
206 // Tests that TimedWait ignores changes to the system clock.
207 // Test is disabled by default, because it needs to run as root to muck with the
208 // system clock.
209 // http://crbug.com/293736
210 TEST_F(ConditionVariableTest, DISABLED_TimeoutAcrossSetTimeOfDay) {
211 timeval tv;
212 gettimeofday(&tv, NULL);
213 tv.tv_sec += kDiscontinuitySeconds;
214 if (settimeofday(&tv, NULL) < 0) {
215 PLOG(ERROR) << "Could not set time of day. Run as root?";
216 return;
219 Lock lock;
220 ConditionVariable cv(&lock);
221 lock.Acquire();
223 Thread thread("Helper");
224 thread.Start();
225 thread.task_runner()->PostTask(FROM_HERE, base::Bind(&BackInTime, &lock));
227 TimeTicks start = TimeTicks::Now();
228 const TimeDelta kWaitTime = TimeDelta::FromMilliseconds(300);
229 // Allow for clocking rate granularity.
230 const TimeDelta kFudgeTime = TimeDelta::FromMilliseconds(50);
232 cv.TimedWait(kWaitTime + kFudgeTime);
233 TimeDelta duration = TimeTicks::Now() - start;
235 thread.Stop();
236 // We can't use EXPECT_GE here as the TimeDelta class does not support the
237 // required stream conversion.
238 EXPECT_TRUE(duration >= kWaitTime);
239 EXPECT_TRUE(duration <= TimeDelta::FromSeconds(kDiscontinuitySeconds));
241 lock.Release();
243 #endif
246 // Suddenly got flaky on Win, see http://crbug.com/10607 (starting at
247 // comment #15).
248 #if defined(OS_WIN)
249 #define MAYBE_MultiThreadConsumerTest DISABLED_MultiThreadConsumerTest
250 #else
251 #define MAYBE_MultiThreadConsumerTest MultiThreadConsumerTest
252 #endif
253 // Test serial task servicing, as well as two parallel task servicing methods.
254 TEST_F(ConditionVariableTest, MAYBE_MultiThreadConsumerTest) {
255 const int kThreadCount = 10;
256 WorkQueue queue(kThreadCount); // Start the threads.
258 const int kTaskCount = 10; // Number of tasks in each mini-test here.
260 Time start_time; // Used to time task processing.
263 base::AutoLock auto_lock(*queue.lock());
264 while (!queue.EveryIdWasAllocated())
265 queue.all_threads_have_ids()->Wait();
268 // If threads aren't in a wait state, they may start to gobble up tasks in
269 // parallel, short-circuiting (breaking) this test.
270 queue.SpinUntilAllThreadsAreWaiting();
273 // Since we have no tasks yet, all threads should be waiting by now.
274 base::AutoLock auto_lock(*queue.lock());
275 EXPECT_EQ(0, queue.GetNumThreadsTakingAssignments());
276 EXPECT_EQ(0, queue.GetNumThreadsCompletingTasks());
277 EXPECT_EQ(0, queue.task_count());
278 EXPECT_EQ(0, queue.GetMaxCompletionsByWorkerThread());
279 EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
280 EXPECT_EQ(0, queue.GetNumberOfCompletedTasks());
282 // Set up to make each task include getting help from another worker, so
283 // so that the work gets done in paralell.
284 queue.ResetHistory();
285 queue.SetTaskCount(kTaskCount);
286 queue.SetWorkTime(kThirtyMs);
287 queue.SetAllowHelp(true);
289 start_time = Time::Now();
292 queue.work_is_available()->Signal(); // But each worker can signal another.
293 // Wait till we at least start to handle tasks (and we're not all waiting).
294 queue.SpinUntilTaskCountLessThan(kTaskCount);
295 // Wait to allow the all workers to get done.
296 queue.SpinUntilAllThreadsAreWaiting();
299 // Wait until all work tasks have at least been assigned.
300 base::AutoLock auto_lock(*queue.lock());
301 while (queue.task_count())
302 queue.no_more_tasks()->Wait();
304 // To avoid racy assumptions, we'll just assert that at least 2 threads
305 // did work. We know that the first worker should have gone to sleep, and
306 // hence a second worker should have gotten an assignment.
307 EXPECT_LE(2, queue.GetNumThreadsTakingAssignments());
308 EXPECT_EQ(kTaskCount, queue.GetNumberOfCompletedTasks());
310 // Try to ask all workers to help, and only a few will do the work.
311 queue.ResetHistory();
312 queue.SetTaskCount(3);
313 queue.SetWorkTime(kThirtyMs);
314 queue.SetAllowHelp(false);
316 queue.work_is_available()->Broadcast(); // Make them all try.
317 // Wait till we at least start to handle tasks (and we're not all waiting).
318 queue.SpinUntilTaskCountLessThan(3);
319 // Wait to allow the 3 workers to get done.
320 queue.SpinUntilAllThreadsAreWaiting();
323 base::AutoLock auto_lock(*queue.lock());
324 EXPECT_EQ(3, queue.GetNumThreadsTakingAssignments());
325 EXPECT_EQ(3, queue.GetNumThreadsCompletingTasks());
326 EXPECT_EQ(0, queue.task_count());
327 EXPECT_EQ(1, queue.GetMaxCompletionsByWorkerThread());
328 EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
329 EXPECT_EQ(3, queue.GetNumberOfCompletedTasks());
331 // Set up to make each task get help from another worker.
332 queue.ResetHistory();
333 queue.SetTaskCount(3);
334 queue.SetWorkTime(kThirtyMs);
335 queue.SetAllowHelp(true); // Allow (unnecessary) help requests.
337 queue.work_is_available()->Broadcast(); // Signal all threads.
338 // Wait till we at least start to handle tasks (and we're not all waiting).
339 queue.SpinUntilTaskCountLessThan(3);
340 // Wait to allow the 3 workers to get done.
341 queue.SpinUntilAllThreadsAreWaiting();
344 base::AutoLock auto_lock(*queue.lock());
345 EXPECT_EQ(3, queue.GetNumThreadsTakingAssignments());
346 EXPECT_EQ(3, queue.GetNumThreadsCompletingTasks());
347 EXPECT_EQ(0, queue.task_count());
348 EXPECT_EQ(1, queue.GetMaxCompletionsByWorkerThread());
349 EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
350 EXPECT_EQ(3, queue.GetNumberOfCompletedTasks());
352 // Set up to make each task get help from another worker.
353 queue.ResetHistory();
354 queue.SetTaskCount(20); // 2 tasks per thread.
355 queue.SetWorkTime(kThirtyMs);
356 queue.SetAllowHelp(true);
358 queue.work_is_available()->Signal(); // But each worker can signal another.
359 // Wait till we at least start to handle tasks (and we're not all waiting).
360 queue.SpinUntilTaskCountLessThan(20);
361 // Wait to allow the 10 workers to get done.
362 queue.SpinUntilAllThreadsAreWaiting(); // Should take about 60 ms.
365 base::AutoLock auto_lock(*queue.lock());
366 EXPECT_EQ(10, queue.GetNumThreadsTakingAssignments());
367 EXPECT_EQ(10, queue.GetNumThreadsCompletingTasks());
368 EXPECT_EQ(0, queue.task_count());
369 EXPECT_EQ(20, queue.GetNumberOfCompletedTasks());
371 // Same as last test, but with Broadcast().
372 queue.ResetHistory();
373 queue.SetTaskCount(20); // 2 tasks per thread.
374 queue.SetWorkTime(kThirtyMs);
375 queue.SetAllowHelp(true);
377 queue.work_is_available()->Broadcast();
378 // Wait till we at least start to handle tasks (and we're not all waiting).
379 queue.SpinUntilTaskCountLessThan(20);
380 // Wait to allow the 10 workers to get done.
381 queue.SpinUntilAllThreadsAreWaiting(); // Should take about 60 ms.
384 base::AutoLock auto_lock(*queue.lock());
385 EXPECT_EQ(10, queue.GetNumThreadsTakingAssignments());
386 EXPECT_EQ(10, queue.GetNumThreadsCompletingTasks());
387 EXPECT_EQ(0, queue.task_count());
388 EXPECT_EQ(20, queue.GetNumberOfCompletedTasks());
390 queue.SetShutdown();
392 queue.work_is_available()->Broadcast(); // Force check for shutdown.
394 SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(1),
395 queue.ThreadSafeCheckShutdown(kThreadCount));
398 TEST_F(ConditionVariableTest, LargeFastTaskTest) {
399 const int kThreadCount = 200;
400 WorkQueue queue(kThreadCount); // Start the threads.
402 Lock private_lock; // Used locally for master to wait.
403 base::AutoLock private_held_lock(private_lock);
404 ConditionVariable private_cv(&private_lock);
407 base::AutoLock auto_lock(*queue.lock());
408 while (!queue.EveryIdWasAllocated())
409 queue.all_threads_have_ids()->Wait();
412 // Wait a bit more to allow threads to reach their wait state.
413 queue.SpinUntilAllThreadsAreWaiting();
416 // Since we have no tasks, all threads should be waiting by now.
417 base::AutoLock auto_lock(*queue.lock());
418 EXPECT_EQ(0, queue.GetNumThreadsTakingAssignments());
419 EXPECT_EQ(0, queue.GetNumThreadsCompletingTasks());
420 EXPECT_EQ(0, queue.task_count());
421 EXPECT_EQ(0, queue.GetMaxCompletionsByWorkerThread());
422 EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
423 EXPECT_EQ(0, queue.GetNumberOfCompletedTasks());
425 // Set up to make all workers do (an average of) 20 tasks.
426 queue.ResetHistory();
427 queue.SetTaskCount(20 * kThreadCount);
428 queue.SetWorkTime(kFortyFiveMs);
429 queue.SetAllowHelp(false);
431 queue.work_is_available()->Broadcast(); // Start up all threads.
432 // Wait until we've handed out all tasks.
434 base::AutoLock auto_lock(*queue.lock());
435 while (queue.task_count() != 0)
436 queue.no_more_tasks()->Wait();
439 // Wait till the last of the tasks complete.
440 queue.SpinUntilAllThreadsAreWaiting();
443 // With Broadcast(), every thread should have participated.
444 // but with racing.. they may not all have done equal numbers of tasks.
445 base::AutoLock auto_lock(*queue.lock());
446 EXPECT_EQ(kThreadCount, queue.GetNumThreadsTakingAssignments());
447 EXPECT_EQ(kThreadCount, queue.GetNumThreadsCompletingTasks());
448 EXPECT_EQ(0, queue.task_count());
449 EXPECT_LE(20, queue.GetMaxCompletionsByWorkerThread());
450 EXPECT_EQ(20 * kThreadCount, queue.GetNumberOfCompletedTasks());
452 // Set up to make all workers do (an average of) 4 tasks.
453 queue.ResetHistory();
454 queue.SetTaskCount(kThreadCount * 4);
455 queue.SetWorkTime(kFortyFiveMs);
456 queue.SetAllowHelp(true); // Might outperform Broadcast().
458 queue.work_is_available()->Signal(); // Start up one thread.
460 // Wait until we've handed out all tasks
462 base::AutoLock auto_lock(*queue.lock());
463 while (queue.task_count() != 0)
464 queue.no_more_tasks()->Wait();
467 // Wait till the last of the tasks complete.
468 queue.SpinUntilAllThreadsAreWaiting();
471 // With Signal(), every thread should have participated.
472 // but with racing.. they may not all have done four tasks.
473 base::AutoLock auto_lock(*queue.lock());
474 EXPECT_EQ(kThreadCount, queue.GetNumThreadsTakingAssignments());
475 EXPECT_EQ(kThreadCount, queue.GetNumThreadsCompletingTasks());
476 EXPECT_EQ(0, queue.task_count());
477 EXPECT_LE(4, queue.GetMaxCompletionsByWorkerThread());
478 EXPECT_EQ(4 * kThreadCount, queue.GetNumberOfCompletedTasks());
480 queue.SetShutdown();
482 queue.work_is_available()->Broadcast(); // Force check for shutdown.
484 // Wait for shutdowns to complete.
485 SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(TimeDelta::FromMinutes(1),
486 queue.ThreadSafeCheckShutdown(kThreadCount));
489 //------------------------------------------------------------------------------
490 // Finally we provide the implementation for the methods in the WorkQueue class.
491 //------------------------------------------------------------------------------
493 WorkQueue::WorkQueue(int thread_count)
494 : lock_(),
495 work_is_available_(&lock_),
496 all_threads_have_ids_(&lock_),
497 no_more_tasks_(&lock_),
498 thread_count_(thread_count),
499 waiting_thread_count_(0),
500 thread_handles_(new PlatformThreadHandle[thread_count]),
501 assignment_history_(thread_count),
502 completion_history_(thread_count),
503 thread_started_counter_(0),
504 shutdown_task_count_(0),
505 task_count_(0),
506 allow_help_requests_(false),
507 shutdown_(false) {
508 EXPECT_GE(thread_count_, 1);
509 ResetHistory();
510 SetTaskCount(0);
511 SetWorkTime(TimeDelta::FromMilliseconds(30));
513 for (int i = 0; i < thread_count_; ++i) {
514 PlatformThreadHandle pth;
515 EXPECT_TRUE(PlatformThread::Create(0, this, &pth));
516 thread_handles_[i] = pth;
520 WorkQueue::~WorkQueue() {
522 base::AutoLock auto_lock(lock_);
523 SetShutdown();
525 work_is_available_.Broadcast(); // Tell them all to terminate.
527 for (int i = 0; i < thread_count_; ++i) {
528 PlatformThread::Join(thread_handles_[i]);
530 EXPECT_EQ(0, waiting_thread_count_);
533 int WorkQueue::GetThreadId() {
534 DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
535 DCHECK(!EveryIdWasAllocated());
536 return thread_started_counter_++; // Give out Unique IDs.
539 bool WorkQueue::EveryIdWasAllocated() const {
540 DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
541 return thread_count_ == thread_started_counter_;
544 TimeDelta WorkQueue::GetAnAssignment(int thread_id) {
545 DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
546 DCHECK_LT(0, task_count_);
547 assignment_history_[thread_id]++;
548 if (0 == --task_count_) {
549 no_more_tasks_.Signal();
551 return worker_delay_;
554 void WorkQueue::WorkIsCompleted(int thread_id) {
555 DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
556 completion_history_[thread_id]++;
559 int WorkQueue::task_count() const {
560 DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
561 return task_count_;
564 bool WorkQueue::allow_help_requests() const {
565 DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
566 return allow_help_requests_;
569 bool WorkQueue::shutdown() const {
570 lock_.AssertAcquired();
571 DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
572 return shutdown_;
575 // Because this method is called from the test's main thread we need to actually
576 // take the lock. Threads will call the thread_shutting_down() method with the
577 // lock already acquired.
578 bool WorkQueue::ThreadSafeCheckShutdown(int thread_count) {
579 bool all_shutdown;
580 base::AutoLock auto_lock(lock_);
582 // Declare in scope so DFAKE is guranteed to be destroyed before AutoLock.
583 DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
584 all_shutdown = (shutdown_task_count_ == thread_count);
586 return all_shutdown;
589 void WorkQueue::thread_shutting_down() {
590 lock_.AssertAcquired();
591 DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
592 shutdown_task_count_++;
595 Lock* WorkQueue::lock() {
596 return &lock_;
599 ConditionVariable* WorkQueue::work_is_available() {
600 return &work_is_available_;
603 ConditionVariable* WorkQueue::all_threads_have_ids() {
604 return &all_threads_have_ids_;
607 ConditionVariable* WorkQueue::no_more_tasks() {
608 return &no_more_tasks_;
611 void WorkQueue::ResetHistory() {
612 for (int i = 0; i < thread_count_; ++i) {
613 assignment_history_[i] = 0;
614 completion_history_[i] = 0;
618 int WorkQueue::GetMinCompletionsByWorkerThread() const {
619 int minumum = completion_history_[0];
620 for (int i = 0; i < thread_count_; ++i)
621 minumum = std::min(minumum, completion_history_[i]);
622 return minumum;
625 int WorkQueue::GetMaxCompletionsByWorkerThread() const {
626 int maximum = completion_history_[0];
627 for (int i = 0; i < thread_count_; ++i)
628 maximum = std::max(maximum, completion_history_[i]);
629 return maximum;
632 int WorkQueue::GetNumThreadsTakingAssignments() const {
633 int count = 0;
634 for (int i = 0; i < thread_count_; ++i)
635 if (assignment_history_[i])
636 count++;
637 return count;
640 int WorkQueue::GetNumThreadsCompletingTasks() const {
641 int count = 0;
642 for (int i = 0; i < thread_count_; ++i)
643 if (completion_history_[i])
644 count++;
645 return count;
648 int WorkQueue::GetNumberOfCompletedTasks() const {
649 int total = 0;
650 for (int i = 0; i < thread_count_; ++i)
651 total += completion_history_[i];
652 return total;
655 void WorkQueue::SetWorkTime(TimeDelta delay) {
656 worker_delay_ = delay;
659 void WorkQueue::SetTaskCount(int count) {
660 task_count_ = count;
663 void WorkQueue::SetAllowHelp(bool allow) {
664 allow_help_requests_ = allow;
667 void WorkQueue::SetShutdown() {
668 lock_.AssertAcquired();
669 shutdown_ = true;
672 void WorkQueue::SpinUntilAllThreadsAreWaiting() {
673 while (true) {
675 base::AutoLock auto_lock(lock_);
676 if (waiting_thread_count_ == thread_count_)
677 break;
679 PlatformThread::Sleep(TimeDelta::FromMilliseconds(30));
683 void WorkQueue::SpinUntilTaskCountLessThan(int task_count) {
684 while (true) {
686 base::AutoLock auto_lock(lock_);
687 if (task_count_ < task_count)
688 break;
690 PlatformThread::Sleep(TimeDelta::FromMilliseconds(30));
695 //------------------------------------------------------------------------------
696 // Define the standard worker task. Several tests will spin out many of these
697 // threads.
698 //------------------------------------------------------------------------------
700 // The multithread tests involve several threads with a task to perform as
701 // directed by an instance of the class WorkQueue.
702 // The task is to:
703 // a) Check to see if there are more tasks (there is a task counter).
704 // a1) Wait on condition variable if there are no tasks currently.
705 // b) Call a function to see what should be done.
706 // c) Do some computation based on the number of milliseconds returned in (b).
707 // d) go back to (a).
709 // WorkQueue::ThreadMain() implements the above task for all threads.
710 // It calls the controlling object to tell the creator about progress, and to
711 // ask about tasks.
713 void WorkQueue::ThreadMain() {
714 int thread_id;
716 base::AutoLock auto_lock(lock_);
717 thread_id = GetThreadId();
718 if (EveryIdWasAllocated())
719 all_threads_have_ids()->Signal(); // Tell creator we're ready.
722 Lock private_lock; // Used to waste time on "our work".
723 while (1) { // This is the main consumer loop.
724 TimeDelta work_time;
725 bool could_use_help;
727 base::AutoLock auto_lock(lock_);
728 while (0 == task_count() && !shutdown()) {
729 ++waiting_thread_count_;
730 work_is_available()->Wait();
731 --waiting_thread_count_;
733 if (shutdown()) {
734 // Ack the notification of a shutdown message back to the controller.
735 thread_shutting_down();
736 return; // Terminate.
738 // Get our task duration from the queue.
739 work_time = GetAnAssignment(thread_id);
740 could_use_help = (task_count() > 0) && allow_help_requests();
741 } // Release lock
743 // Do work (outside of locked region.
744 if (could_use_help)
745 work_is_available()->Signal(); // Get help from other threads.
747 if (work_time > TimeDelta::FromMilliseconds(0)) {
748 // We could just sleep(), but we'll instead further exercise the
749 // condition variable class, and do a timed wait.
750 base::AutoLock auto_lock(private_lock);
751 ConditionVariable private_cv(&private_lock);
752 private_cv.TimedWait(work_time); // Unsynchronized waiting.
756 base::AutoLock auto_lock(lock_);
757 // Send notification that we completed our "work."
758 WorkIsCompleted(thread_id);
763 } // namespace
765 } // namespace base