blob: 3e11c7289fab1487020e702b4dbefe9cbc0975d4 [file] [log] [blame]
Wind Yuan75564b12015-01-15 06:51:15 -05001/*
2 * safe_list.h - safe list template
3 *
4 * Copyright (c) 2014 Intel Corporation
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * Author: Wind Yuan <feng.yuan@intel.com>
19 */
20
21#ifndef XCAM_SAFE_LIST_H
22#define XCAM_SAFE_LIST_H
23
Wind Yuan29a49f52015-01-26 17:57:37 +080024#include <base/xcam_defs.h>
25#include <base/xcam_common.h>
Wind Yuan75564b12015-01-15 06:51:15 -050026#include <errno.h>
27#include <list>
Wind Yuan29a49f52015-01-26 17:57:37 +080028#include "smartptr.h"
29#include "xcam_mutex.h"
Wind Yuan75564b12015-01-15 06:51:15 -050030
31namespace XCam {
32
33template<class OBj>
34class SafeList {
35public:
36 typedef SmartPtr<OBj> ObjPtr;
37
38 SafeList () {}
39 ~SafeList () {
40 }
41
42 /*
43 * timeout, -1, wait until wakeup
44 * >=0, wait for @timeout microsseconds
45 */
46 inline ObjPtr pop (int32_t timeout = -1);
47 inline bool push (ObjPtr &obj);
48 uint32_t size () {
49 SmartLock lock(_mutex);
50 return _obj_list.size();
51 }
52 bool is_empty () {
53 SmartLock lock(_mutex);
54 return _obj_list.empty();
55 }
56 void wakeup () {
57 _new_obj_cond.broadcast ();
58 }
59 inline void clear ();
60
61private:
62 std::list<ObjPtr> _obj_list;
63 Mutex _mutex;
64 XCam::Cond _new_obj_cond;
65};
66
67
68template<class OBj>
69typename SafeList<OBj>::ObjPtr
70SafeList<OBj>::pop (int32_t timeout)
71{
72 SmartLock lock (_mutex);
73 int code = 0;
74
75 if (_obj_list.empty()) {
76 if (timeout < 0)
77 code = _new_obj_cond.wait(_mutex);
78 else
79 code = _new_obj_cond.timedwait(_mutex, timeout);
80 }
81
82 if (_obj_list.empty()) {
83 if (code == ETIMEDOUT) {
84 XCAM_LOG_DEBUG ("safe list pop timeout");
85 } else {
86 XCAM_LOG_DEBUG ("safe list pop failed");
87 }
88 return NULL;
89 }
90
91 SafeList<OBj>::ObjPtr obj = *_obj_list.begin ();
92 _obj_list.erase (_obj_list.begin ());
93 return obj;
94}
95
96template<class OBj>
97bool
98SafeList<OBj>::push (SafeList<OBj>::ObjPtr &obj)
99{
100 SmartLock lock (_mutex);
101 _obj_list.push_back (obj);
102 _new_obj_cond.signal ();
103 return true;
104}
105
106template<class OBj>
107void SafeList<OBj>::clear ()
108{
109 SmartLock lock (_mutex);
110 typename std::list<typename SafeList<OBj>::ObjPtr>::iterator i_obj = _obj_list.begin ();
111 while (i_obj != _obj_list.end ()) {
112 _obj_list.erase (i_obj++);
113 }
114}
115
116};
117#endif //XCAM_SAFE_LIST_H