-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathThreadBase.cpp
More file actions
63 lines (50 loc) · 1.21 KB
/
ThreadBase.cpp
File metadata and controls
63 lines (50 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include "ThreadBase.h"
#include <cassert>
ThreadBase::ThreadBase() : m_running_b(false)
{
pthread_mutex_init(&m_mutex_b, NULL);
pthread_cond_init(&m_cond_b, NULL);
}
ThreadBase::~ThreadBase()
{
assert(!m_running_b);
pthread_cond_destroy(&m_cond_b);
pthread_mutex_destroy(&m_mutex_b);
}
bool
ThreadBase::spawn()
{
pthread_mutex_lock(&m_mutex_b);
pthread_t threadId;
const int ret = pthread_create(&threadId, NULL, &ThreadBase::svcRun, this);
if (ret == -1)
{
pthread_mutex_unlock(&m_mutex_b);
return false;
}
m_running_b = true;
pthread_mutex_unlock(&m_mutex_b);
return true;
}
void
ThreadBase::wait()
{
pthread_mutex_lock(&m_mutex_b);
while (m_running_b)
{
///< the mutex param of 'pthread_cond_wait()' MUST not be null, and MUST be LOCKED.
pthread_cond_wait(&m_cond_b, &m_mutex_b);
}
pthread_mutex_unlock(&m_mutex_b);
}
void *
ThreadBase::svcRun(void * arg)
{
ThreadBase * const thread = (ThreadBase *)arg;
thread->svc();
pthread_mutex_lock(&thread->m_mutex_b);
thread->m_running_b = false;
pthread_cond_signal(&thread->m_cond_b);
pthread_mutex_unlock(&thread->m_mutex_b);
return 0;
}