summaryrefslogtreecommitdiffstats
path: root/base/threading/worker_pool_posix.cc
blob: 231aa68deafa31e84493dbf534ae384288e19461 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/threading/worker_pool_posix.h"

#include "base/bind.h"
#include "base/callback.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/strings/stringprintf.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread_local.h"
#include "base/threading/worker_pool.h"
#include "base/trace_event/trace_event.h"
#include "base/tracked_objects.h"

using tracked_objects::TrackedTime;

namespace base {

namespace {

LazyInstance<ThreadLocalBoolean>::Leaky g_worker_pool_running_on_this_thread =
    LAZY_INSTANCE_INITIALIZER;

const int64 kIdleSecondsBeforeExit = 10 * 60;

class WorkerPoolImpl {
 public:
  WorkerPoolImpl();
  ~WorkerPoolImpl();

  void PostTask(const tracked_objects::Location& from_here,
                const Closure& task,
                bool task_is_slow);

  void ShutDownCleanly();

 private:
  scoped_refptr<PosixDynamicThreadPool> pool_;
};

WorkerPoolImpl::WorkerPoolImpl()
    : pool_(new PosixDynamicThreadPool(
          "WorkerPool",
          TimeDelta::FromSeconds(kIdleSecondsBeforeExit))) {
}

WorkerPoolImpl::~WorkerPoolImpl() {
  pool_->Terminate(false);
}

void WorkerPoolImpl::PostTask(const tracked_objects::Location& from_here,
                              const Closure& task,
                              bool task_is_slow) {
  pool_->PostTask(from_here, task);
}

void WorkerPoolImpl::ShutDownCleanly() {
  pool_->Terminate(true);
}

LazyInstance<WorkerPoolImpl> g_lazy_worker_pool = LAZY_INSTANCE_INITIALIZER;

class WorkerThread : public PlatformThread::Delegate {
 public:
  WorkerThread(const std::string& name_prefix, PosixDynamicThreadPool* pool)
      : name_prefix_(name_prefix), pool_(pool) {}

  void ThreadMain() override;

 private:
  const std::string name_prefix_;
  scoped_refptr<PosixDynamicThreadPool> pool_;

  DISALLOW_COPY_AND_ASSIGN(WorkerThread);
};

void WorkerThread::ThreadMain() {
  g_worker_pool_running_on_this_thread.Get().Set(true);
  const std::string name =
      StringPrintf("%s/%d", name_prefix_.c_str(), PlatformThread::CurrentId());
  // Note |name.c_str()| must remain valid for for the whole life of the thread.
  PlatformThread::SetName(name);

  for (;;) {
    PendingTask pending_task = pool_->WaitForTask();
    if (pending_task.task.is_null())
      break;
    TRACE_EVENT2("toplevel", "WorkerThread::ThreadMain::Run",
        "src_file", pending_task.posted_from.file_name(),
        "src_func", pending_task.posted_from.function_name());

    tracked_objects::TaskStopwatch stopwatch;
    stopwatch.Start();
    pending_task.task.Run();
    stopwatch.Stop();

    tracked_objects::ThreadData::TallyRunOnWorkerThreadIfTracking(
        pending_task.birth_tally, pending_task.time_posted, stopwatch);
  }

  pool_->NotifyWorkerIsGoingAway(PlatformThread::CurrentHandle());
  delete this;
}

}  // namespace

// static
bool WorkerPool::PostTask(const tracked_objects::Location& from_here,
                          const Closure& task,
                          bool task_is_slow) {
  g_lazy_worker_pool.Pointer()->PostTask(from_here, task, task_is_slow);
  return true;
}

// static
bool WorkerPool::RunsTasksOnCurrentThread() {
  return g_worker_pool_running_on_this_thread.Get().Get();
}

// static
void WorkerPool::ShutDownCleanly() {
  g_lazy_worker_pool.Pointer()->ShutDownCleanly();
}

PosixDynamicThreadPool::PosixDynamicThreadPool(const std::string& name_prefix,
                                               TimeDelta idle_time_before_exit)
    : name_prefix_(name_prefix),
      idle_time_before_exit_(idle_time_before_exit),
      pending_tasks_available_cv_(&lock_),
      num_idle_threads_(0),
      has_pending_cleanup_task_(false),
      terminated_(false) {
}

PosixDynamicThreadPool::~PosixDynamicThreadPool() {
  while (!pending_tasks_.empty())
    pending_tasks_.pop();
}

void PosixDynamicThreadPool::Terminate(bool blocking) {
  std::vector<PlatformThreadHandle> threads_to_cleanup;
  std::vector<PlatformThreadHandle> worker_threads;
  {
    AutoLock locked(lock_);
    if (terminated_)
      return;
    terminated_ = true;

    threads_to_cleanup.swap(threads_to_cleanup_);
    worker_threads.swap(worker_threads_);
  }
  pending_tasks_available_cv_.Broadcast();

  if (blocking) {
    for (const auto& item : threads_to_cleanup)
      PlatformThread::Join(item);

    for (const auto& item : worker_threads)
      PlatformThread::Join(item);

    // No need to take the lock. No one else should be accessing these members.
    DCHECK_EQ(0u, num_idle_threads_);
    // The following members should not have new elements added after
    // |terminated_| is set to true.
    DCHECK(threads_to_cleanup_.empty());
    DCHECK(worker_threads_.empty());
  }
}

void PosixDynamicThreadPool::PostTask(
    const tracked_objects::Location& from_here,
    const Closure& task) {
  PendingTask pending_task(from_here, task);
  AutoLock locked(lock_);
  AddTaskNoLock(&pending_task);
}

PendingTask PosixDynamicThreadPool::WaitForTask() {
  AutoLock locked(lock_);

  if (terminated_)
    return PendingTask(FROM_HERE, Closure());

  if (pending_tasks_.empty()) {  // No work available, wait for work.
    num_idle_threads_++;
    if (num_threads_cv_)
      num_threads_cv_->Broadcast();
    pending_tasks_available_cv_.TimedWait(idle_time_before_exit_);
    num_idle_threads_--;
    if (num_threads_cv_)
      num_threads_cv_->Broadcast();
    if (pending_tasks_.empty()) {
      // We waited for work, but there's still no work.  Return an empty task to
      // signal the thread to terminate.
      return PendingTask(FROM_HERE, Closure());
    }
  }

  PendingTask pending_task = pending_tasks_.front();
  pending_tasks_.pop();
  return pending_task;
}

void PosixDynamicThreadPool::NotifyWorkerIsGoingAway(
    PlatformThreadHandle worker) {
  AutoLock locked(lock_);
  if (terminated_)
    return;

  auto new_end = std::remove_if(worker_threads_.begin(), worker_threads_.end(),
                                [worker](PlatformThreadHandle handle) {
                                  return handle.is_equal(worker);
                                });
  DCHECK_EQ(1, worker_threads_.end() - new_end);
  worker_threads_.erase(new_end, worker_threads_.end());

  threads_to_cleanup_.push_back(worker);

  if (num_threads_cv_)
    num_threads_cv_->Broadcast();

  if (!has_pending_cleanup_task_) {
    has_pending_cleanup_task_ = true;
    PendingTask pending_task(
        FROM_HERE,
        base::Bind(&PosixDynamicThreadPool::CleanUpThreads, Unretained(this)));
    AddTaskNoLock(&pending_task);
  }
}

void PosixDynamicThreadPool::AddTaskNoLock(PendingTask* pending_task) {
  lock_.AssertAcquired();

  if (terminated_) {
    LOG(WARNING)
        << "This thread pool is already terminated.  Do not post new tasks.";
    return;
  }

  pending_tasks_.push(*pending_task);
  pending_task->task.Reset();

  // We have enough worker threads.
  if (num_idle_threads_ >=
      pending_tasks_.size() - (has_pending_cleanup_task_ ? 1 : 0)) {
    pending_tasks_available_cv_.Signal();
  } else {
    // The new PlatformThread will take ownership of the WorkerThread object,
    // which will delete itself on exit.
    WorkerThread* worker = new WorkerThread(name_prefix_, this);
    PlatformThreadHandle handle;
    PlatformThread::Create(0, worker, &handle);
    worker_threads_.push_back(handle);

    if (num_threads_cv_)
      num_threads_cv_->Broadcast();
  }
}

void PosixDynamicThreadPool::CleanUpThreads() {
  std::vector<PlatformThreadHandle> threads_to_cleanup;
  {
    AutoLock locked(lock_);
    DCHECK(has_pending_cleanup_task_);
    has_pending_cleanup_task_ = false;
    threads_to_cleanup.swap(threads_to_cleanup_);
  }
  for (const auto& item : threads_to_cleanup)
    PlatformThread::Join(item);
}

}  // namespace base