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.
5 #ifndef LIBRARIES_SDK_UTIL_THREAD_SAFE_QUEUE_H_
6 #define LIBRARIES_SDK_UTIL_THREAD_SAFE_QUEUE_H_
12 #include "sdk_util/auto_lock.h"
13 #include "sdk_util/macros.h"
19 // A simple template to support multithreaded and optionally blocking access
20 // to a Queue of object pointers.
22 template<class T
> class ThreadSafeQueue
{
25 pthread_cond_init(&cond_
, NULL
);
29 pthread_cond_destroy(&cond_
);
32 void Enqueue(T
* item
) {
34 list_
.push_back(item
);
36 pthread_cond_signal(&cond_
);
39 T
* Dequeue(bool block
) {
42 // If blocking enabled, wait until we queue is non-empty
44 while (list_
.empty()) pthread_cond_wait(&cond_
, lock_
.mutex());
47 if (list_
.empty()) return NULL
;
49 T
* item
= list_
.front();
58 DISALLOW_COPY_AND_ASSIGN(ThreadSafeQueue
);
61 } // namespace sdk_util
63 #endif // LIBRARIES_SDK_UTIL_THREAD_SAFE_QUEUE_H_