1// Copyright (c) 2013 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// Simple thread pool class
6
7#ifndef LIBRARIES_SDK_UTIL_THREAD_POOL_H_
8#define LIBRARIES_SDK_UTIL_THREAD_POOL_H_
9
10#include <pthread.h>
11#include <semaphore.h>
12
13#include "sdk_util/atomicops.h"
14
15namespace sdk_util {
16
17// typdef helper for work function
18typedef void (*WorkFunction)(int task_index, void* data);
19
20// ThreadPool is a class to manage num_threads and assign
21// them num_tasks of work at a time. Each call
22// to Dispatch(..) will block until all tasks complete.
23// If 0 is passed in for num_threads, all tasks will be
24// issued on the dispatch thread.
25
26class ThreadPool {
27 public:
28  void Dispatch(int num_tasks, WorkFunction work, void* data);
29  explicit ThreadPool(int num_threads);
30  ~ThreadPool();
31 private:
32  int DecCounter();
33  void Setup(int counter, WorkFunction work, void* data);
34  void DispatchMany(int num_tasks, WorkFunction work, void* data);
35  void DispatchHere(int num_tasks, WorkFunction work, void* data);
36  void WorkLoop();
37  static void* WorkerThreadEntry(void* data);
38  void PostExitAndJoinAll();
39  pthread_t* threads_;
40  Atomic32 counter_;
41  const int num_threads_;
42  bool exiting_;
43  void* user_data_;
44  WorkFunction user_work_function_;
45  sem_t work_sem_;
46  sem_t done_sem_;
47};
48
49}  // namespace sdk_util
50
51#endif  // LIBRARIES_SDK_UTIL_THREAD_POOL_H_
52
53