OLD | NEW |
(Empty) | |
| 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 #ifndef LIBRARIES_SDK_UTIL_THREAD_SAFE_QUEUE_H_ |
| 6 #define LIBRARIES_SDK_UTIL_THREAD_SAFE_QUEUE_H_ |
| 7 |
| 8 #include <pthread.h> |
| 9 |
| 10 #include <list> |
| 11 |
| 12 #include "sdk_util/auto_lock.h" |
| 13 #include "sdk_util/macros.h" |
| 14 |
| 15 |
| 16 // ThreadSafeQueue |
| 17 // |
| 18 // A simple template to support multithreaded and optionally blocking access |
| 19 // to a Queue of object pointers. |
| 20 // |
| 21 template<class T> class ThreadSafeQueue { |
| 22 public: |
| 23 ThreadSafeQueue() { |
| 24 pthread_mutex_init(&mutex_, NULL); |
| 25 pthread_cond_init(&cond_, NULL); |
| 26 } |
| 27 |
| 28 ~ThreadSafeQueue() { |
| 29 pthread_mutex_destroy(&mutex_); |
| 30 pthread_cond_destroy(&cond_); |
| 31 } |
| 32 |
| 33 void Enqueue(T* item) { |
| 34 AutoLock lock(&mutex_); |
| 35 list_.push_back(item); |
| 36 |
| 37 pthread_cond_signal(&cond_); |
| 38 } |
| 39 |
| 40 T* Dequeue(bool block) { |
| 41 AutoLock lock(&mutex_); |
| 42 |
| 43 // If blocking enabled, wait until we queue is non-empty |
| 44 if (block) { |
| 45 while (list_.empty()) pthread_cond_wait(&cond_, &mutex_); |
| 46 } |
| 47 |
| 48 if (list_.empty()) return NULL; |
| 49 |
| 50 T* item = list_.front(); |
| 51 list_.pop_front(); |
| 52 return item; |
| 53 } |
| 54 |
| 55 private: |
| 56 std::list<T*> list_; |
| 57 pthread_cond_t cond_; |
| 58 pthread_mutex_t mutex_; |
| 59 DISALLOW_COPY_AND_ASSIGN(ThreadSafeQueue); |
| 60 }; |
| 61 |
| 62 #endif // LIBRARIES_SDK_UTIL_THREAD_SAFE_QUEUE_H_ |
| 63 |
OLD | NEW |