]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/threadengines/threadengine_pthread.cpp
Thread safety stuff, waiting for pointer to become 'safe' before changing it (e.g...
[user/henk/code/inspircd.git] / src / threadengines / threadengine_pthread.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include "inspircd.h"
15 #include "threadengines/threadengine_pthread.h"
16 #include <pthread.h>
17
18 pthread_mutex_t MyMutex = PTHREAD_MUTEX_INITIALIZER;
19
20 PThreadEngine::PThreadEngine(InspIRCd* Instance) : ThreadEngine(Instance)
21 {
22 }
23
24 void PThreadEngine::Create(Thread* thread_to_init)
25 {
26         pthread_attr_t attribs;
27         pthread_attr_init(&attribs);
28         pthread_attr_setdetachstate(&attribs, PTHREAD_CREATE_JOINABLE);
29         pthread_t* MyPThread = new pthread_t;
30
31         Mutex(true);
32
33         if (pthread_create(MyPThread, &attribs, PThreadEngine::Entry, (void*)this) != 0)
34         {
35                 delete MyPThread;
36                 Mutex(false);
37                 throw CoreException("Unable to create new PThreadEngine: " + std::string(strerror(errno)));
38         }
39
40         pthread_attr_destroy(&attribs);
41
42         NewThread = thread_to_init;
43         NewThread->Creator = this;
44         NewThread->Extend("pthread", MyPThread);
45
46         Mutex(false);
47
48         while (NewThread)
49                 usleep(1000);
50 }
51
52 PThreadEngine::~PThreadEngine()
53 {
54 }
55
56 void PThreadEngine::Run()
57 {
58         Mutex(true);
59         Thread* nt = NewThread;
60         NewThread = NULL;
61         Mutex(false);
62         nt->Run();
63 }
64
65 bool PThreadEngine::Mutex(bool enable)
66 {
67         if (enable)
68                 pthread_mutex_lock(&MyMutex);
69         else
70                 pthread_mutex_unlock(&MyMutex);
71
72         return false;
73 }
74
75 void* PThreadEngine::Entry(void* parameter)
76 {
77         ThreadEngine * pt = (ThreadEngine*)parameter;
78         pt->Run();
79         return NULL;
80 }
81
82 void PThreadEngine::FreeThread(Thread* thread)
83 {
84         pthread_t* pthread = NULL;
85         if (thread->GetExt("pthread", pthread))
86         {
87                 thread->SetExitFlag();
88                 int rc;
89                 void* status;
90                 rc = pthread_join(*pthread, &status);
91                 delete pthread;
92         }
93 }
94