1 // Copyright 2018 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 #include "base/task/thread_pool/pooled_task_runner_delegate.h" 6 7 #include "base/debug/task_trace.h" 8 #include "base/logging.h" 9 10 namespace base { 11 namespace internal { 12 13 namespace { 14 15 // Stores the current PooledTaskRunnerDelegate in this process(null if none). 16 // Used to tell when a task is posted from the main thread after the 17 // task environment was brought down in unit tests so that TaskRunners can 18 // return false on PostTask, letting callers know they should complete 19 // necessary work synchronously. A PooledTaskRunnerDelegate is usually 20 // instantiated before worker threads are started and deleted after worker 21 // threads have been joined. This makes the variable const while worker threads 22 // are up and as such it doesn't need to be atomic. 23 // Also used to tell if an attempt is made to run a task after its 24 // task runner's delegate is no longer the current delegate, i.e., a task runner 25 // is created in one unit test and posted to in a subsequent test, due to global 26 // state leaking between tests. 27 PooledTaskRunnerDelegate* g_current_delegate = nullptr; 28 29 } // namespace 30 PooledTaskRunnerDelegate()31PooledTaskRunnerDelegate::PooledTaskRunnerDelegate() { 32 DCHECK(!g_current_delegate); 33 g_current_delegate = this; 34 } 35 ~PooledTaskRunnerDelegate()36PooledTaskRunnerDelegate::~PooledTaskRunnerDelegate() { 37 DCHECK(g_current_delegate); 38 g_current_delegate = nullptr; 39 } 40 41 // static MatchesCurrentDelegate(PooledTaskRunnerDelegate * delegate)42bool PooledTaskRunnerDelegate::MatchesCurrentDelegate( 43 PooledTaskRunnerDelegate* delegate) { 44 if (g_current_delegate && g_current_delegate != delegate) { 45 LOG(ERROR) 46 << "Stale pooled_task_runner_delegate_ - task not posted. This is\n" 47 "almost certainly caused by a previous test leaving a stale task\n" 48 "runner in a global object, and a subsequent test triggering the\n " 49 "global object to post a task to the stale task runner.\n" 50 << base::debug::StackTrace(); 51 } 52 return g_current_delegate == delegate; 53 } 54 55 } // namespace internal 56 } // namespace base 57