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