- add sources.
[platform/framework/web/crosswalk.git] / src / native_client_sdk / src / libraries / sdk_util / thread_safe_queue.h
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 namespace sdk_util {
16
17 // ThreadSafeQueue
18 //
19 // A simple template to support multithreaded and optionally blocking access
20 // to a Queue of object pointers.
21 //
22 template<class T> class ThreadSafeQueue {
23  public:
24   ThreadSafeQueue() {
25     pthread_cond_init(&cond_, NULL);
26   }
27
28   ~ThreadSafeQueue() {
29     pthread_cond_destroy(&cond_);
30   }
31
32   void Enqueue(T* item) {
33     AUTO_LOCK(lock_);
34     list_.push_back(item);
35
36     pthread_cond_signal(&cond_);
37   }
38
39   T* Dequeue(bool block) {
40     AUTO_LOCK(lock_);
41
42     // If blocking enabled, wait until we queue is non-empty
43     if (block) {
44       while (list_.empty()) pthread_cond_wait(&cond_, lock_.mutex());
45     }
46
47     if (list_.empty()) return NULL;
48
49     T* item = list_.front();
50     list_.pop_front();
51     return item;
52   }
53
54  private:
55   std::list<T*> list_;
56   pthread_cond_t  cond_;
57   SimpleLock lock_;
58   DISALLOW_COPY_AND_ASSIGN(ThreadSafeQueue);
59 };
60
61 }  // namespace sdk_util
62
63 #endif  // LIBRARIES_SDK_UTIL_THREAD_SAFE_QUEUE_H_
64