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
27 pthread_mutex_init(&lock, NULL);
28 }
29
Thread(RunnableInterface * r)30 Thread::Thread(RunnableInterface *r)
31 {
32 this->r = r;
33 created = false;
34
35 pthread_mutex_init(&lock, NULL);
36 }
37
~Thread()38 Thread::~Thread()
39 {
40 Join();
41
42 pthread_mutex_destroy(&lock);
43 }
44
Start(void)45 int Thread::Start(void)
46 {
47 int ret = 0;
48
49 pthread_mutex_lock(&lock);
50 if (!created) {
51 ret = pthread_create(&id, NULL, Instance, this);
52 if (!ret)
53 created = true;
54 }
55 pthread_mutex_unlock(&lock);
56
57 return ret;
58 }
59
Join(void)60 int Thread::Join(void)
61 {
62 int ret = 0;
63
64 pthread_mutex_lock(&lock);
65 if (created) {
66 ret = pthread_join(id, NULL);
67 created = false;
68 }
69 pthread_mutex_unlock(&lock);
70
71 return ret;
72 }
73
Instance(void * p)74 void *Thread::Instance(void *p)
75 {
76 Thread *t = static_cast<Thread *>(p);
77
78 t->Run();
79
80 return NULL;
81 }
82
Run(void)83 void Thread::Run(void)
84 {
85 if (r)
86 r->Run();
87 else
88 return;
89 }
90