• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // Multi-threaded tests of ConditionVariable class.
6 
7 #include "base/synchronization/condition_variable.h"
8 
9 #include <time.h>
10 
11 #include <algorithm>
12 #include <memory>
13 #include <vector>
14 
15 #include "base/functional/bind.h"
16 #include "base/location.h"
17 #include "base/logging.h"
18 #include "base/synchronization/lock.h"
19 #include "base/task/single_thread_task_runner.h"
20 #include "base/test/spin_wait.h"
21 #include "base/threading/platform_thread.h"
22 #include "base/threading/thread.h"
23 #include "base/threading/thread_collision_warner.h"
24 #include "base/time/time.h"
25 #include "build/build_config.h"
26 #include "testing/gtest/include/gtest/gtest.h"
27 #include "testing/platform_test.h"
28 
29 namespace base {
30 
31 namespace {
32 //------------------------------------------------------------------------------
33 // Define our test class, with several common variables.
34 //------------------------------------------------------------------------------
35 
36 class ConditionVariableTest : public PlatformTest {
37  public:
38   const TimeDelta kZeroMs;
39   const TimeDelta kTenMs;
40   const TimeDelta kThirtyMs;
41   const TimeDelta kFortyFiveMs;
42   const TimeDelta kSixtyMs;
43   const TimeDelta kOneHundredMs;
44 
ConditionVariableTest()45   ConditionVariableTest()
46       : kZeroMs(Milliseconds(0)),
47         kTenMs(Milliseconds(10)),
48         kThirtyMs(Milliseconds(30)),
49         kFortyFiveMs(Milliseconds(45)),
50         kSixtyMs(Milliseconds(60)),
51         kOneHundredMs(Milliseconds(100)) {}
52 };
53 
54 //------------------------------------------------------------------------------
55 // Define a class that will control activities an several multi-threaded tests.
56 // The general structure of multi-threaded tests is that a test case will
57 // construct an instance of a WorkQueue.  The WorkQueue will spin up some
58 // threads and control them throughout their lifetime, as well as maintaining
59 // a central repository of the work thread's activity.  Finally, the WorkQueue
60 // will command the worker threads to terminate.  At that point, the test
61 // cases will validate that the WorkQueue has records showing that the desired
62 // activities were performed.
63 //------------------------------------------------------------------------------
64 
65 // Callers are responsible for synchronizing access to the following class.
66 // The WorkQueue::lock_, as accessed via WorkQueue::lock(), should be used for
67 // all synchronized access.
68 class WorkQueue : public PlatformThread::Delegate {
69  public:
70   explicit WorkQueue(int thread_count);
71   ~WorkQueue() override;
72 
73   // PlatformThread::Delegate interface.
74   void ThreadMain() override;
75 
76   //----------------------------------------------------------------------------
77   // Worker threads only call the following methods.
78   // They should use the lock to get exclusive access.
79   int GetThreadId();  // Get an ID assigned to a thread..
80   bool EveryIdWasAllocated() const;  // Indicates that all IDs were handed out.
81   TimeDelta GetAnAssignment(int thread_id);  // Get a work task duration.
82   void WorkIsCompleted(int thread_id);
83 
84   int task_count() const;
85   bool allow_help_requests() const;  // Workers can signal more workers.
86   bool shutdown() const;  // Check if shutdown has been requested.
87 
88   void thread_shutting_down();
89 
90 
91   //----------------------------------------------------------------------------
92   // Worker threads can call them but not needed to acquire a lock.
93   Lock* lock();
94 
95   ConditionVariable* work_is_available();
96   ConditionVariable* all_threads_have_ids();
97   ConditionVariable* no_more_tasks();
98 
99   //----------------------------------------------------------------------------
100   // The rest of the methods are for use by the controlling master thread (the
101   // test case code).
102   void ResetHistory();
103   int GetMinCompletionsByWorkerThread() const;
104   int GetMaxCompletionsByWorkerThread() const;
105   int GetNumThreadsTakingAssignments() const;
106   int GetNumThreadsCompletingTasks() const;
107   int GetNumberOfCompletedTasks() const;
108 
109   void SetWorkTime(TimeDelta delay);
110   void SetTaskCount(int count);
111   void SetAllowHelp(bool allow);
112 
113   // The following must be called without locking, and will spin wait until the
114   // threads are all in a wait state.
115   void SpinUntilAllThreadsAreWaiting();
116   void SpinUntilTaskCountLessThan(int task_count);
117 
118   // Caller must acquire lock before calling.
119   void SetShutdown();
120 
121   // Compares the |shutdown_task_count_| to the |thread_count| and returns true
122   // if they are equal.  This check will acquire the |lock_| so the caller
123   // should not hold the lock when calling this method.
124   bool ThreadSafeCheckShutdown(int thread_count);
125 
126  private:
127   // Both worker threads and controller use the following to synchronize.
128   Lock lock_;
129   ConditionVariable work_is_available_;  // To tell threads there is work.
130 
131   // Conditions to notify the controlling process (if it is interested).
132   ConditionVariable all_threads_have_ids_;  // All threads are running.
133   ConditionVariable no_more_tasks_;  // Task count is zero.
134 
135   const int thread_count_;
136   int waiting_thread_count_;
137   std::unique_ptr<PlatformThreadHandle[]> thread_handles_;
138   std::vector<int> assignment_history_;  // Number of assignment per worker.
139   std::vector<int> completion_history_;  // Number of completions per worker.
140   int thread_started_counter_;  // Used to issue unique id to workers.
141   int shutdown_task_count_;  // Number of tasks told to shutdown
142   int task_count_;  // Number of assignment tasks waiting to be processed.
143   TimeDelta worker_delay_;  // Time each task takes to complete.
144   bool allow_help_requests_;  // Workers can signal more workers.
145   bool shutdown_;  // Set when threads need to terminate.
146 
147   DFAKE_MUTEX(locked_methods_);
148 };
149 
150 //------------------------------------------------------------------------------
151 // The next section contains the actual tests.
152 //------------------------------------------------------------------------------
153 
TEST_F(ConditionVariableTest,StartupShutdownTest)154 TEST_F(ConditionVariableTest, StartupShutdownTest) {
155   Lock lock;
156 
157   // First try trivial startup/shutdown.
158   {
159     ConditionVariable cv1(&lock);
160   }  // Call for cv1 destruction.
161 
162   // Exercise with at least a few waits.
163   ConditionVariable cv(&lock);
164 
165   lock.Acquire();
166   cv.TimedWait(kTenMs);  // Wait for 10 ms.
167   cv.TimedWait(kTenMs);  // Wait for 10 ms.
168   lock.Release();
169 
170   lock.Acquire();
171   cv.TimedWait(kTenMs);  // Wait for 10 ms.
172   cv.TimedWait(kTenMs);  // Wait for 10 ms.
173   cv.TimedWait(kTenMs);  // Wait for 10 ms.
174   lock.Release();
175 }  // Call for cv destruction.
176 
TEST_F(ConditionVariableTest,TimeoutTest)177 TEST_F(ConditionVariableTest, TimeoutTest) {
178   Lock lock;
179   ConditionVariable cv(&lock);
180   lock.Acquire();
181 
182   TimeTicks start = TimeTicks::Now();
183   const TimeDelta WAIT_TIME = Milliseconds(300);
184   // Allow for clocking rate granularity.
185   const TimeDelta FUDGE_TIME = Milliseconds(50);
186 
187   cv.TimedWait(WAIT_TIME + FUDGE_TIME);
188   TimeDelta duration = TimeTicks::Now() - start;
189   // We can't use EXPECT_GE here as the TimeDelta class does not support the
190   // required stream conversion.
191   EXPECT_TRUE(duration >= WAIT_TIME);
192 
193   lock.Release();
194 }
195 
196 #if BUILDFLAG(IS_POSIX)
197 const int kDiscontinuitySeconds = 2;
198 
BackInTime(Lock * lock)199 void BackInTime(Lock* lock) {
200   AutoLock auto_lock(*lock);
201 
202   timeval tv;
203   gettimeofday(&tv, nullptr);
204   tv.tv_sec -= kDiscontinuitySeconds;
205   settimeofday(&tv, nullptr);
206 }
207 
208 // Tests that TimedWait ignores changes to the system clock.
209 // Test is disabled by default, because it needs to run as root to muck with the
210 // system clock.
211 // http://crbug.com/293736
TEST_F(ConditionVariableTest,DISABLED_TimeoutAcrossSetTimeOfDay)212 TEST_F(ConditionVariableTest, DISABLED_TimeoutAcrossSetTimeOfDay) {
213   timeval tv;
214   gettimeofday(&tv, nullptr);
215   tv.tv_sec += kDiscontinuitySeconds;
216   if (settimeofday(&tv, nullptr) < 0) {
217     PLOG(ERROR) << "Could not set time of day. Run as root?";
218     return;
219   }
220 
221   Lock lock;
222   ConditionVariable cv(&lock);
223   lock.Acquire();
224 
225   Thread thread("Helper");
226   thread.Start();
227   thread.task_runner()->PostTask(FROM_HERE, base::BindOnce(&BackInTime, &lock));
228 
229   TimeTicks start = TimeTicks::Now();
230   const TimeDelta kWaitTime = Milliseconds(300);
231   // Allow for clocking rate granularity.
232   const TimeDelta kFudgeTime = Milliseconds(50);
233 
234   cv.TimedWait(kWaitTime + kFudgeTime);
235   TimeDelta duration = TimeTicks::Now() - start;
236 
237   thread.Stop();
238   // We can't use EXPECT_GE here as the TimeDelta class does not support the
239   // required stream conversion.
240   EXPECT_TRUE(duration >= kWaitTime);
241   EXPECT_TRUE(duration <= Seconds(kDiscontinuitySeconds));
242 
243   lock.Release();
244 }
245 #endif
246 
247 // Test serial task servicing, as well as two parallel task servicing methods.
TEST_F(ConditionVariableTest,MultiThreadConsumerTest)248 TEST_F(ConditionVariableTest, MultiThreadConsumerTest) {
249   const int kThreadCount = 10;
250   WorkQueue queue(kThreadCount);  // Start the threads.
251 
252   const int kTaskCount = 10;  // Number of tasks in each mini-test here.
253 
254   Time start_time;  // Used to time task processing.
255 
256   {
257     base::AutoLock auto_lock(*queue.lock());
258     while (!queue.EveryIdWasAllocated())
259       queue.all_threads_have_ids()->Wait();
260   }
261 
262   // If threads aren't in a wait state, they may start to gobble up tasks in
263   // parallel, short-circuiting (breaking) this test.
264   queue.SpinUntilAllThreadsAreWaiting();
265 
266   {
267     // Since we have no tasks yet, all threads should be waiting by now.
268     base::AutoLock auto_lock(*queue.lock());
269     EXPECT_EQ(0, queue.GetNumThreadsTakingAssignments());
270     EXPECT_EQ(0, queue.GetNumThreadsCompletingTasks());
271     EXPECT_EQ(0, queue.task_count());
272     EXPECT_EQ(0, queue.GetMaxCompletionsByWorkerThread());
273     EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
274     EXPECT_EQ(0, queue.GetNumberOfCompletedTasks());
275 
276     // Set up to make each task include getting help from another worker, so
277     // so that the work gets done in paralell.
278     queue.ResetHistory();
279     queue.SetTaskCount(kTaskCount);
280     queue.SetWorkTime(kThirtyMs);
281     queue.SetAllowHelp(true);
282 
283     start_time = Time::Now();
284   }
285 
286   queue.work_is_available()->Signal();  // But each worker can signal another.
287   // Wait till we at least start to handle tasks (and we're not all waiting).
288   queue.SpinUntilTaskCountLessThan(kTaskCount);
289   // Wait to allow the all workers to get done.
290   queue.SpinUntilAllThreadsAreWaiting();
291 
292   {
293     // Wait until all work tasks have at least been assigned.
294     base::AutoLock auto_lock(*queue.lock());
295     while (queue.task_count())
296       queue.no_more_tasks()->Wait();
297 
298     // To avoid racy assumptions, we'll just assert that at least 2 threads
299     // did work.  We know that the first worker should have gone to sleep, and
300     // hence a second worker should have gotten an assignment.
301     EXPECT_LE(2, queue.GetNumThreadsTakingAssignments());
302     EXPECT_EQ(kTaskCount, queue.GetNumberOfCompletedTasks());
303 
304     // Try to ask all workers to help, and only a few will do the work.
305     queue.ResetHistory();
306     queue.SetTaskCount(3);
307     queue.SetWorkTime(kThirtyMs);
308     queue.SetAllowHelp(false);
309   }
310   queue.work_is_available()->Broadcast();  // Make them all try.
311   // Wait till we at least start to handle tasks (and we're not all waiting).
312   queue.SpinUntilTaskCountLessThan(3);
313   // Wait to allow the 3 workers to get done.
314   queue.SpinUntilAllThreadsAreWaiting();
315 
316   {
317     base::AutoLock auto_lock(*queue.lock());
318     EXPECT_EQ(3, queue.GetNumThreadsTakingAssignments());
319     EXPECT_EQ(3, queue.GetNumThreadsCompletingTasks());
320     EXPECT_EQ(0, queue.task_count());
321     EXPECT_EQ(1, queue.GetMaxCompletionsByWorkerThread());
322     EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
323     EXPECT_EQ(3, queue.GetNumberOfCompletedTasks());
324 
325     // Set up to make each task get help from another worker.
326     queue.ResetHistory();
327     queue.SetTaskCount(3);
328     queue.SetWorkTime(kThirtyMs);
329     queue.SetAllowHelp(true);  // Allow (unnecessary) help requests.
330   }
331   queue.work_is_available()->Broadcast();  // Signal all threads.
332   // Wait till we at least start to handle tasks (and we're not all waiting).
333   queue.SpinUntilTaskCountLessThan(3);
334   // Wait to allow the 3 workers to get done.
335   queue.SpinUntilAllThreadsAreWaiting();
336 
337   {
338     base::AutoLock auto_lock(*queue.lock());
339     EXPECT_EQ(3, queue.GetNumThreadsTakingAssignments());
340     EXPECT_EQ(3, queue.GetNumThreadsCompletingTasks());
341     EXPECT_EQ(0, queue.task_count());
342     EXPECT_EQ(1, queue.GetMaxCompletionsByWorkerThread());
343     EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
344     EXPECT_EQ(3, queue.GetNumberOfCompletedTasks());
345 
346     // Set up to make each task get help from another worker.
347     queue.ResetHistory();
348     queue.SetTaskCount(20);  // 2 tasks per thread.
349     queue.SetWorkTime(kThirtyMs);
350     queue.SetAllowHelp(true);
351   }
352   queue.work_is_available()->Signal();  // But each worker can signal another.
353   // Wait till we at least start to handle tasks (and we're not all waiting).
354   queue.SpinUntilTaskCountLessThan(20);
355   // Wait to allow the 10 workers to get done.
356   queue.SpinUntilAllThreadsAreWaiting();  // Should take about 60 ms.
357 
358   {
359     base::AutoLock auto_lock(*queue.lock());
360     EXPECT_EQ(10, queue.GetNumThreadsTakingAssignments());
361     EXPECT_EQ(10, queue.GetNumThreadsCompletingTasks());
362     EXPECT_EQ(0, queue.task_count());
363     EXPECT_EQ(20, queue.GetNumberOfCompletedTasks());
364 
365     // Same as last test, but with Broadcast().
366     queue.ResetHistory();
367     queue.SetTaskCount(20);  // 2 tasks per thread.
368     queue.SetWorkTime(kThirtyMs);
369     queue.SetAllowHelp(true);
370   }
371   queue.work_is_available()->Broadcast();
372   // Wait till we at least start to handle tasks (and we're not all waiting).
373   queue.SpinUntilTaskCountLessThan(20);
374   // Wait to allow the 10 workers to get done.
375   queue.SpinUntilAllThreadsAreWaiting();  // Should take about 60 ms.
376 
377   {
378     base::AutoLock auto_lock(*queue.lock());
379     EXPECT_EQ(10, queue.GetNumThreadsTakingAssignments());
380     EXPECT_EQ(10, queue.GetNumThreadsCompletingTasks());
381     EXPECT_EQ(0, queue.task_count());
382     EXPECT_EQ(20, queue.GetNumberOfCompletedTasks());
383 
384     queue.SetShutdown();
385   }
386   queue.work_is_available()->Broadcast();  // Force check for shutdown.
387 
388   SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(Minutes(1),
389                                    queue.ThreadSafeCheckShutdown(kThreadCount));
390 }
391 
TEST_F(ConditionVariableTest,LargeFastTaskTest)392 TEST_F(ConditionVariableTest, LargeFastTaskTest) {
393   const int kThreadCount = 200;
394   WorkQueue queue(kThreadCount);  // Start the threads.
395 
396   Lock private_lock;  // Used locally for master to wait.
397   base::AutoLock private_held_lock(private_lock);
398   ConditionVariable private_cv(&private_lock);
399 
400   {
401     base::AutoLock auto_lock(*queue.lock());
402     while (!queue.EveryIdWasAllocated())
403       queue.all_threads_have_ids()->Wait();
404   }
405 
406   // Wait a bit more to allow threads to reach their wait state.
407   queue.SpinUntilAllThreadsAreWaiting();
408 
409   {
410     // Since we have no tasks, all threads should be waiting by now.
411     base::AutoLock auto_lock(*queue.lock());
412     EXPECT_EQ(0, queue.GetNumThreadsTakingAssignments());
413     EXPECT_EQ(0, queue.GetNumThreadsCompletingTasks());
414     EXPECT_EQ(0, queue.task_count());
415     EXPECT_EQ(0, queue.GetMaxCompletionsByWorkerThread());
416     EXPECT_EQ(0, queue.GetMinCompletionsByWorkerThread());
417     EXPECT_EQ(0, queue.GetNumberOfCompletedTasks());
418 
419     // Set up to make all workers do (an average of) 20 tasks.
420     queue.ResetHistory();
421     queue.SetTaskCount(20 * kThreadCount);
422     queue.SetWorkTime(kFortyFiveMs);
423     queue.SetAllowHelp(false);
424   }
425   queue.work_is_available()->Broadcast();  // Start up all threads.
426   // Wait until we've handed out all tasks.
427   {
428     base::AutoLock auto_lock(*queue.lock());
429     while (queue.task_count() != 0)
430       queue.no_more_tasks()->Wait();
431   }
432 
433   // Wait till the last of the tasks complete.
434   queue.SpinUntilAllThreadsAreWaiting();
435 
436   {
437     // With Broadcast(), every thread should have participated.
438     // but with racing.. they may not all have done equal numbers of tasks.
439     base::AutoLock auto_lock(*queue.lock());
440     EXPECT_EQ(kThreadCount, queue.GetNumThreadsTakingAssignments());
441     EXPECT_EQ(kThreadCount, queue.GetNumThreadsCompletingTasks());
442     EXPECT_EQ(0, queue.task_count());
443     EXPECT_LE(20, queue.GetMaxCompletionsByWorkerThread());
444     EXPECT_EQ(20 * kThreadCount, queue.GetNumberOfCompletedTasks());
445 
446     // Set up to make all workers do (an average of) 4 tasks.
447     queue.ResetHistory();
448     queue.SetTaskCount(kThreadCount * 4);
449     queue.SetWorkTime(kFortyFiveMs);
450     queue.SetAllowHelp(true);  // Might outperform Broadcast().
451   }
452   queue.work_is_available()->Signal();  // Start up one thread.
453 
454   // Wait until we've handed out all tasks
455   {
456     base::AutoLock auto_lock(*queue.lock());
457     while (queue.task_count() != 0)
458       queue.no_more_tasks()->Wait();
459   }
460 
461   // Wait till the last of the tasks complete.
462   queue.SpinUntilAllThreadsAreWaiting();
463 
464   {
465     // With Signal(), every thread should have participated.
466     // but with racing.. they may not all have done four tasks.
467     base::AutoLock auto_lock(*queue.lock());
468     EXPECT_EQ(kThreadCount, queue.GetNumThreadsTakingAssignments());
469     EXPECT_EQ(kThreadCount, queue.GetNumThreadsCompletingTasks());
470     EXPECT_EQ(0, queue.task_count());
471     EXPECT_LE(4, queue.GetMaxCompletionsByWorkerThread());
472     EXPECT_EQ(4 * kThreadCount, queue.GetNumberOfCompletedTasks());
473 
474     queue.SetShutdown();
475   }
476   queue.work_is_available()->Broadcast();  // Force check for shutdown.
477 
478   // Wait for shutdowns to complete.
479   SPIN_FOR_TIMEDELTA_OR_UNTIL_TRUE(Minutes(1),
480                                    queue.ThreadSafeCheckShutdown(kThreadCount));
481 }
482 
483 //------------------------------------------------------------------------------
484 // Finally we provide the implementation for the methods in the WorkQueue class.
485 //------------------------------------------------------------------------------
486 
WorkQueue(int thread_count)487 WorkQueue::WorkQueue(int thread_count)
488   : lock_(),
489     work_is_available_(&lock_),
490     all_threads_have_ids_(&lock_),
491     no_more_tasks_(&lock_),
492     thread_count_(thread_count),
493     waiting_thread_count_(0),
494     thread_handles_(new PlatformThreadHandle[thread_count]),
495     assignment_history_(thread_count),
496     completion_history_(thread_count),
497     thread_started_counter_(0),
498     shutdown_task_count_(0),
499     task_count_(0),
500     allow_help_requests_(false),
501     shutdown_(false) {
502   EXPECT_GE(thread_count_, 1);
503   ResetHistory();
504   SetTaskCount(0);
505   SetWorkTime(Milliseconds(30));
506 
507   for (int i = 0; i < thread_count_; ++i) {
508     PlatformThreadHandle pth;
509     EXPECT_TRUE(PlatformThread::Create(0, this, &pth));
510     thread_handles_[i] = pth;
511   }
512 }
513 
~WorkQueue()514 WorkQueue::~WorkQueue() {
515   {
516     base::AutoLock auto_lock(lock_);
517     SetShutdown();
518   }
519   work_is_available_.Broadcast();  // Tell them all to terminate.
520 
521   for (int i = 0; i < thread_count_; ++i) {
522     PlatformThread::Join(thread_handles_[i]);
523   }
524   EXPECT_EQ(0, waiting_thread_count_);
525 }
526 
GetThreadId()527 int WorkQueue::GetThreadId() {
528   DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
529   DCHECK(!EveryIdWasAllocated());
530   return thread_started_counter_++;  // Give out Unique IDs.
531 }
532 
EveryIdWasAllocated() const533 bool WorkQueue::EveryIdWasAllocated() const {
534   DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
535   return thread_count_ == thread_started_counter_;
536 }
537 
GetAnAssignment(int thread_id)538 TimeDelta WorkQueue::GetAnAssignment(int thread_id) {
539   DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
540   DCHECK_LT(0, task_count_);
541   assignment_history_[thread_id]++;
542   if (0 == --task_count_) {
543     no_more_tasks_.Signal();
544   }
545   return worker_delay_;
546 }
547 
WorkIsCompleted(int thread_id)548 void WorkQueue::WorkIsCompleted(int thread_id) {
549   DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
550   completion_history_[thread_id]++;
551 }
552 
task_count() const553 int WorkQueue::task_count() const {
554   DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
555   return task_count_;
556 }
557 
allow_help_requests() const558 bool WorkQueue::allow_help_requests() const {
559   DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
560   return allow_help_requests_;
561 }
562 
shutdown() const563 bool WorkQueue::shutdown() const {
564   lock_.AssertAcquired();
565   DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
566   return shutdown_;
567 }
568 
569 // Because this method is called from the test's main thread we need to actually
570 // take the lock.  Threads will call the thread_shutting_down() method with the
571 // lock already acquired.
ThreadSafeCheckShutdown(int thread_count)572 bool WorkQueue::ThreadSafeCheckShutdown(int thread_count) {
573   bool all_shutdown;
574   base::AutoLock auto_lock(lock_);
575   {
576     // Declare in scope so DFAKE is guranteed to be destroyed before AutoLock.
577     DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
578     all_shutdown = (shutdown_task_count_ == thread_count);
579   }
580   return all_shutdown;
581 }
582 
thread_shutting_down()583 void WorkQueue::thread_shutting_down() {
584   lock_.AssertAcquired();
585   DFAKE_SCOPED_RECURSIVE_LOCK(locked_methods_);
586   shutdown_task_count_++;
587 }
588 
lock()589 Lock* WorkQueue::lock() {
590   return &lock_;
591 }
592 
work_is_available()593 ConditionVariable* WorkQueue::work_is_available() {
594   return &work_is_available_;
595 }
596 
all_threads_have_ids()597 ConditionVariable* WorkQueue::all_threads_have_ids() {
598   return &all_threads_have_ids_;
599 }
600 
no_more_tasks()601 ConditionVariable* WorkQueue::no_more_tasks() {
602   return &no_more_tasks_;
603 }
604 
ResetHistory()605 void WorkQueue::ResetHistory() {
606   for (int i = 0; i < thread_count_; ++i) {
607     assignment_history_[i] = 0;
608     completion_history_[i] = 0;
609   }
610 }
611 
GetMinCompletionsByWorkerThread() const612 int WorkQueue::GetMinCompletionsByWorkerThread() const {
613   int minumum = completion_history_[0];
614   for (int i = 0; i < thread_count_; ++i)
615     minumum = std::min(minumum, completion_history_[i]);
616   return minumum;
617 }
618 
GetMaxCompletionsByWorkerThread() const619 int WorkQueue::GetMaxCompletionsByWorkerThread() const {
620   int maximum = completion_history_[0];
621   for (int i = 0; i < thread_count_; ++i)
622     maximum = std::max(maximum, completion_history_[i]);
623   return maximum;
624 }
625 
GetNumThreadsTakingAssignments() const626 int WorkQueue::GetNumThreadsTakingAssignments() const {
627   int count = 0;
628   for (int i = 0; i < thread_count_; ++i)
629     if (assignment_history_[i])
630       count++;
631   return count;
632 }
633 
GetNumThreadsCompletingTasks() const634 int WorkQueue::GetNumThreadsCompletingTasks() const {
635   int count = 0;
636   for (int i = 0; i < thread_count_; ++i)
637     if (completion_history_[i])
638       count++;
639   return count;
640 }
641 
GetNumberOfCompletedTasks() const642 int WorkQueue::GetNumberOfCompletedTasks() const {
643   int total = 0;
644   for (int i = 0; i < thread_count_; ++i)
645     total += completion_history_[i];
646   return total;
647 }
648 
SetWorkTime(TimeDelta delay)649 void WorkQueue::SetWorkTime(TimeDelta delay) {
650   worker_delay_ = delay;
651 }
652 
SetTaskCount(int count)653 void WorkQueue::SetTaskCount(int count) {
654   task_count_ = count;
655 }
656 
SetAllowHelp(bool allow)657 void WorkQueue::SetAllowHelp(bool allow) {
658   allow_help_requests_ = allow;
659 }
660 
SetShutdown()661 void WorkQueue::SetShutdown() {
662   lock_.AssertAcquired();
663   shutdown_ = true;
664 }
665 
SpinUntilAllThreadsAreWaiting()666 void WorkQueue::SpinUntilAllThreadsAreWaiting() {
667   while (true) {
668     {
669       base::AutoLock auto_lock(lock_);
670       if (waiting_thread_count_ == thread_count_)
671         break;
672     }
673     PlatformThread::Sleep(Milliseconds(30));
674   }
675 }
676 
SpinUntilTaskCountLessThan(int task_count)677 void WorkQueue::SpinUntilTaskCountLessThan(int task_count) {
678   while (true) {
679     {
680       base::AutoLock auto_lock(lock_);
681       if (task_count_ < task_count)
682         break;
683     }
684     PlatformThread::Sleep(Milliseconds(30));
685   }
686 }
687 
688 
689 //------------------------------------------------------------------------------
690 // Define the standard worker task. Several tests will spin out many of these
691 // threads.
692 //------------------------------------------------------------------------------
693 
694 // The multithread tests involve several threads with a task to perform as
695 // directed by an instance of the class WorkQueue.
696 // The task is to:
697 // a) Check to see if there are more tasks (there is a task counter).
698 //    a1) Wait on condition variable if there are no tasks currently.
699 // b) Call a function to see what should be done.
700 // c) Do some computation based on the number of milliseconds returned in (b).
701 // d) go back to (a).
702 
703 // WorkQueue::ThreadMain() implements the above task for all threads.
704 // It calls the controlling object to tell the creator about progress, and to
705 // ask about tasks.
706 
ThreadMain()707 void WorkQueue::ThreadMain() {
708   int thread_id;
709   {
710     base::AutoLock auto_lock(lock_);
711     thread_id = GetThreadId();
712     if (EveryIdWasAllocated())
713       all_threads_have_ids()->Signal();  // Tell creator we're ready.
714   }
715 
716   Lock private_lock;  // Used to waste time on "our work".
717   while (true) {      // This is the main consumer loop.
718     TimeDelta work_time;
719     bool could_use_help;
720     {
721       base::AutoLock auto_lock(lock_);
722       while (0 == task_count() && !shutdown()) {
723         ++waiting_thread_count_;
724         work_is_available()->Wait();
725         --waiting_thread_count_;
726       }
727       if (shutdown()) {
728         // Ack the notification of a shutdown message back to the controller.
729         thread_shutting_down();
730         return;  // Terminate.
731       }
732       // Get our task duration from the queue.
733       work_time = GetAnAssignment(thread_id);
734       could_use_help = (task_count() > 0) && allow_help_requests();
735     }  // Release lock
736 
737     // Do work (outside of locked region.
738     if (could_use_help)
739       work_is_available()->Signal();  // Get help from other threads.
740 
741     if (work_time > Milliseconds(0)) {
742       // We could just sleep(), but we'll instead further exercise the
743       // condition variable class, and do a timed wait.
744       base::AutoLock auto_lock(private_lock);
745       ConditionVariable private_cv(&private_lock);
746       private_cv.TimedWait(work_time);  // Unsynchronized waiting.
747     }
748 
749     {
750       base::AutoLock auto_lock(lock_);
751       // Send notification that we completed our "work."
752       WorkIsCompleted(thread_id);
753     }
754   }
755 }
756 
757 }  // namespace
758 
759 }  // namespace base
760