| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | |
| 2 // for details. All rights reserved. Use of this source code is governed by a | |
| 3 // BSD-style license that can be found in the LICENSE file. | |
| 4 | |
| 5 #ifndef BIN_THREAD_POOL_H_ | |
| 6 #define BIN_THREAD_POOL_H_ | |
| 7 | |
| 8 #include "bin/builtin.h" | |
| 9 #include "platform/globals.h" | |
| 10 #include "platform/thread.h" | |
| 11 | |
| 12 class ThreadPool { | |
| 13 public: | |
| 14 typedef void* Task; | |
| 15 typedef void (*TaskHandler)(Task args); | |
| 16 | |
| 17 enum DrainFlag { | |
| 18 kDrain, | |
| 19 kDoNotDrain | |
| 20 }; | |
| 21 | |
| 22 ThreadPool(TaskHandler task_handler, int initial_number_of_threads = 4) | |
| 23 : initial_number_of_threads_(initial_number_of_threads), | |
| 24 terminate_(false), | |
| 25 drain_flag_(kDoNotDrain), | |
| 26 number_of_threads_(0), | |
| 27 head_(NULL), | |
| 28 tail_(NULL), | |
| 29 task_handler_(task_handler) {} | |
| 30 | |
| 31 // Start the thread pool. | |
| 32 void Start(); | |
| 33 | |
| 34 // Shutdown the thread pool. The drain flags specifies whether all | |
| 35 // tasks pending in the queue will be processed. When this function | |
| 36 // returns all threads are terminated. | |
| 37 void Shutdown(DrainFlag drain_flag = kDoNotDrain); | |
| 38 | |
| 39 // Insert a new task into the thread pool. Returns true on success. | |
| 40 bool InsertTask(Task task); | |
| 41 | |
| 42 private: | |
| 43 class TaskQueueEntry { | |
| 44 public: | |
| 45 explicit TaskQueueEntry(Task task) : task_(task), next_(NULL) {} | |
| 46 | |
| 47 Task task() { return task_; } | |
| 48 TaskQueueEntry* next() { return next_; } | |
| 49 void set_next(TaskQueueEntry* value) { next_ = value; } | |
| 50 | |
| 51 private: | |
| 52 Task task_; | |
| 53 TaskQueueEntry* next_; | |
| 54 | |
| 55 DISALLOW_COPY_AND_ASSIGN(TaskQueueEntry); | |
| 56 }; | |
| 57 | |
| 58 | |
| 59 TaskQueueEntry* WaitForTask(); | |
| 60 void ThreadTerminated(); | |
| 61 | |
| 62 static void Main(uword args); | |
| 63 | |
| 64 dart::Monitor monitor_; // Monitor protecting all shared state. | |
| 65 | |
| 66 int initial_number_of_threads_; // Initial number of threads to start. | |
| 67 bool terminate_; // Set to true when the thread pool is terminating. | |
| 68 DrainFlag drain_flag_; // Queue handling before termination. | |
| 69 int number_of_threads_; // Current number of threads. | |
| 70 | |
| 71 // The task queue is a single linked list. Link direction is from tail | |
| 72 // to head. New entries are inserted at the tail and entries are | |
| 73 // removed from the head. | |
| 74 TaskQueueEntry* head_; | |
| 75 TaskQueueEntry* tail_; | |
| 76 TaskHandler task_handler_; | |
| 77 | |
| 78 DISALLOW_COPY_AND_ASSIGN(ThreadPool); | |
| 79 }; | |
| 80 | |
| 81 #endif // BIN_THREAD_POOL_H_ | |
| OLD | NEW |