| 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 #include <pthread.h> |
| 6 |
| 7 #include "bin/thread_pool.h" |
| 8 |
| 9 TaskQueue::TaskQueue() : head_(NULL), tail_(NULL) { |
| 10 int result; |
| 11 |
| 12 result = pthread_mutex_init(data_.mutex(), NULL); |
| 13 if (result != 0) { |
| 14 FATAL("pthread_mutex_init failed"); |
| 15 } |
| 16 |
| 17 result = pthread_cond_init(data_.cond(), NULL); |
| 18 if (result != 0) { |
| 19 FATAL("pthread_cond_init failed"); |
| 20 } |
| 21 } |
| 22 |
| 23 |
| 24 void TaskQueue::Insert(TaskQueueEntry* entry) { |
| 25 pthread_mutex_lock(data_.mutex()); |
| 26 if (head_ == NULL) { |
| 27 head_ = entry; |
| 28 tail_ = entry; |
| 29 pthread_cond_signal(data_.cond()); |
| 30 } else { |
| 31 tail_->set_next(entry); |
| 32 tail_ = entry; |
| 33 } |
| 34 pthread_mutex_unlock(data_.mutex()); |
| 35 } |
| 36 |
| 37 |
| 38 TaskQueueEntry* TaskQueue::Remove() { |
| 39 pthread_mutex_lock(data_.mutex()); |
| 40 TaskQueueEntry* result = head_; |
| 41 while (result == NULL) { |
| 42 pthread_cond_wait(data_.cond(), data_.mutex()); |
| 43 result = head_; |
| 44 } |
| 45 head_ = result->next(); |
| 46 ASSERT(head_ != NULL || tail_ == result); |
| 47 pthread_mutex_unlock(data_.mutex()); |
| 48 return result; |
| 49 } |
| 50 |
| 51 |
| 52 void ThreadPool::Start() { |
| 53 pthread_t* threads |
| 54 = reinterpret_cast<pthread_t*>(calloc(size_, sizeof(pthread_t*))); |
| 55 data_.set_threads(threads); |
| 56 for (int i = 0; i < size_; i++) { |
| 57 pthread_t handler_thread; |
| 58 int result = pthread_create(&handler_thread, |
| 59 NULL, |
| 60 &ThreadPool::Main, |
| 61 this); |
| 62 if (result != 0) { |
| 63 FATAL("Create and start thread pool thread"); |
| 64 } |
| 65 data_.threads()[i] = handler_thread; |
| 66 } |
| 67 } |
| OLD | NEW |