blob: 8daa41e91206d42778de1929648962474941f5c2 [file] [log] [blame]
Wind Yuan75564b12015-01-15 06:51:15 -05001/*
2 * xcam_thread.cpp - Thread
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#include "xcam_thread.h"
22#include "xcam_mutex.h"
23
24namespace XCam {
25
26Thread::Thread (const char *name)
27 : _name (NULL)
28 , _thread_id (0)
29 , _started (false)
30{
31 if (name)
32 _name = strdup (name);
33}
34
35Thread::~Thread ()
36{
37 if (_name)
38 xcam_free (_name);
39}
40
41int
42Thread::thread_func (void *user_data)
43{
44 Thread *thread = (Thread *)user_data;
45 bool ret = true;
46
47 {
48 // Make sure running after start
49 SmartLock locker(thread->_mutex);
50 pthread_detach (pthread_self());
51 }
52 ret = thread->started ();
53
54 while (true) {
55 {
56 SmartLock locker(thread->_mutex);
57 if (!thread->_started || ret == false) {
58 thread->_started = false;
59 thread->_thread_id = 0;
60 thread->_exit_cond.signal();
61 ret = false;
62 break;
63 }
64 }
65
66 ret = thread->loop ();
67 }
68
69 thread->stopped ();
70
71 return 0;
72}
73
74bool
75Thread::started ()
76{
77 XCAM_LOG_DEBUG ("Thread(%s) started", XCAM_STR(_name));
78 return true;
79}
80
81void
82Thread::stopped ()
83{
84 XCAM_LOG_DEBUG ("Thread(%s) stopped", XCAM_STR(_name));
85}
86
87bool Thread::start ()
88{
89 SmartLock locker(_mutex);
90 if (_started)
91 return true;
92
93 if (pthread_create (&_thread_id, NULL, (void * (*)(void*))thread_func, this) != 0)
94 return false;
95 _started = true;
96 return true;
97}
98
99bool Thread::stop ()
100{
101 SmartLock locker(_mutex);
102 if (_started) {
103 _started = false;
104 _exit_cond.wait(_mutex);
105 }
106 return true;
107}
108
109bool Thread::is_running ()
110{
111 SmartLock locker(_mutex);
112 return _started;
113}
114
115};