1 /*
2 * thread.cpp, thread class
3 *
4 * Copyright (c) 2009-2010 Wind River Systems, Inc.
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
19 #include <pthread.h>
20 #include <thread.h>
21
Thread()22 Thread::Thread()
23 {
24 r = NULL;
25 created = false;
26 id = 0;
27
28 pthread_mutex_init(&lock, NULL);
29 }
30
Thread(RunnableInterface * r)31 Thread::Thread(RunnableInterface *r)
32 {
33 this->r = r;
34 created = false;
35 id = 0;
36
37 pthread_mutex_init(&lock, NULL);
38 }
39
~Thread()40 Thread::~Thread()
41 {
42 Join();
43
44 pthread_mutex_destroy(&lock);
45 }
46
Start(void)47 int Thread::Start(void)
48 {
49 int ret = 0;
50
51 pthread_mutex_lock(&lock);
52 if (!created) {
53 ret = pthread_create(&id, NULL, Instance, this);
54 if (!ret)
55 created = true;
56 }
57 pthread_mutex_unlock(&lock);
58
59 return ret;
60 }
61
Join(void)62 int Thread::Join(void)
63 {
64 int ret = 0;
65
66 pthread_mutex_lock(&lock);
67 if (created) {
68 ret = pthread_join(id, NULL);
69 created = false;
70 }
71 pthread_mutex_unlock(&lock);
72
73 return ret;
74 }
75
Instance(void * p)76 void *Thread::Instance(void *p)
77 {
78 Thread *t = static_cast<Thread *>(p);
79
80 t->Run();
81
82 return NULL;
83 }
84
Run(void)85 void Thread::Run(void)
86 {
87 if (r)
88 r->Run();
89 else
90 return;
91 }
92