]> granicus.if.org Git - icinga2/commitdiff
Implemented the thread class.
authorGunnar Beutner <gunnar.beutner@netways.de>
Sat, 31 Mar 2012 07:36:00 +0000 (09:36 +0200)
committerGunnar Beutner <gunnar.beutner@netways.de>
Sat, 31 Mar 2012 07:36:00 +0000 (09:36 +0200)
base/i2-base.h
base/thread.cpp [new file with mode: 0644]
base/thread.h [new file with mode: 0644]

index 8ba5d3f8ac849510376829f545dc724b8383e099..c0c302a6f2ddfea57634220cf17cc9fbf29b005d 100644 (file)
@@ -35,6 +35,7 @@
 
 #include "mutex.h"
 #include "condvar.h"
+#include "thread.h"
 #include "object.h"
 #include "memory.h"
 #include "delegate.h"
diff --git a/base/thread.cpp b/base/thread.cpp
new file mode 100644 (file)
index 0000000..32ef506
--- /dev/null
@@ -0,0 +1,69 @@
+#include "i2-base.h"
+
+using namespace icinga;
+
+typedef struct threadparam_s
+{
+       void (*callback)(void*);
+       void *param;
+} threadparam_t;
+
+#ifdef _WIN32
+static DWORD WINAPI ThreadStartProc(LPVOID param)
+{
+       threadparam_t *tparam = (threadparam_t *)param;
+       tparam->callback(tparam->param);
+       delete tparam;
+       return 0;
+}
+#else /* _WIN32 */
+static void *ThreadStartProc(void *param)
+{
+       threadparam_t *tparam = (threadparam_t *)param;
+       tparam->callback(tparam->param);
+       delete tparam;
+       return NULL;
+}
+#endif /* _WIN32 */
+
+
+thread::thread(void (*callback)(void *))
+{
+       threadparam_t *tparam = new threadparam_t();
+
+       if (tparam == NULL)
+               throw exception(/*"Out of memory"*/);
+
+#ifdef _WIN32
+       m_Thread = CreateThread(NULL, 0, ThreadStartProc, tparam, CREATE_SUSPENDED, NULL);
+#else /* _WIN32 */
+       pthread_create(&m_Thread, NULL, ThreadStartProc, &tparam);
+#endif /* _WIN32 */
+}
+
+thread::~thread(void)
+{
+#ifdef _WIN32
+       CloseHandle(m_Thread);
+#else /* _WIN32 */
+       /* nothing to do here */
+#endif
+}
+       
+void thread::terminate(void)
+{
+#ifdef _WIN32
+       TerminateThread(m_Thread, 0);
+#else /* _WIN32 */
+       /* nothing to do here */
+#endif
+}
+
+void thread::join(void)
+{
+#ifdef _WIN32
+       WaitForSingleObject(m_Thread, INFINITE);
+#else /* _WIN32 */
+       pthread_join(m_Thread, NULL);
+#endif
+}
\ No newline at end of file
diff --git a/base/thread.h b/base/thread.h
new file mode 100644 (file)
index 0000000..39d7c97
--- /dev/null
@@ -0,0 +1,29 @@
+#ifndef I2_THREAD_H
+#define I2_THREAD_H
+
+namespace icinga
+{
+
+using std::function;
+
+class thread
+{
+private:
+#ifdef _WIN32
+       HANDLE m_Thread;
+#else
+       pthread_t m_Thread;
+#endif
+
+public:
+       thread(void (*callback)(void *));
+       ~thread(void);
+
+       void start(void);
+       void terminate(void);
+       void join(void);
+};
+
+}
+
+#endif /* I2_THREAD_H */