-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreadable.cpp
65 lines (56 loc) · 1.41 KB
/
Threadable.cpp
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
64
65
//
// Threadable.cpp for plazza in /home/jowett_j//pj/plazza/svn
//
// Made by james jowett
// Login <[email protected]>
//
// Started on Tue Apr 10 05:28:45 2012 james jowett
// Last update Mon Jul 30 03:08:59 2012 Pierre WILMOT
//
#include "Threadable.hpp"
Threadable::Threadable()
: m_mustQuitMutex(Mutex::Normal), m_mustQuit(false), m_launched(false)
{
}
void Threadable::threadIt()
{
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
errno = 0;
m_launched = true;
if (pthread_create(&m_thread, &attr, Threadable::entryPoint, this) != 0)
{
m_launched = false;
throw std::runtime_error(std::string("pthread_create(3): ") + strerror(errno));
}
pthread_attr_destroy(&attr);
}
bool Threadable::mustQuit()
{
bool ret;
bool gotLock;
m_mustQuitMutex.trylock(gotLock);
if (!gotLock)
return false;
ret = m_mustQuit;
m_mustQuitMutex.unlock();
return ret;
}
void *Threadable::entryPoint(void *instance)
{
Threadable *toLaunch;
toLaunch = reinterpret_cast<Threadable *>(instance);
return reinterpret_cast<void *>(toLaunch->threadEntryPoint());
}
Threadable::~Threadable()
{
if (m_launched)
{
m_mustQuitMutex.lock();
m_mustQuit = true;
m_mustQuitMutex.unlock();
if (pthread_join(m_thread, NULL) != 0)
std::cerr << "!! Failed to join with thread !!" << std::endl;
}
}