00001 /* 00002 * lib/threads/thread.h 00003 * 00004 * Implementing thread class for multi-threaded applications. 00005 * 00006 * Copyright (c) 2004 by Wolfgang Wieser ] wwieser (a) gmx <*> de [ 00007 * 00008 * This file may be distributed and/or modified under the terms of the 00009 * GNU General Public License version 2 as published by the Free Software 00010 * Foundation. (See COPYING.GPL for details.) 00011 * 00012 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE 00013 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. 00014 * 00015 */ 00016 00017 #ifndef _ThreadLibrary_Thread_H_ 00018 #define _ThreadLibrary_Thread_H_ 1 00019 00026 #include <lib/sconfig.h> /* MUST be first */ 00027 00028 #include <lib/tl/linkedlist.h> 00029 #include <lib/threads/mutex.h> 00030 00031 #include <glib/gthread.h> 00032 00033 // As defined below. 00034 class ExecutionThread; 00035 00036 00049 class ThreadKernel 00050 { 00051 friend class ExecutionThread; 00052 private: 00054 static ThreadKernel *kernel; 00055 00056 struct TNode : LinkedListBase<TNode> 00057 { 00058 // Actual thread structure. 00059 GThread *thread; 00060 // Associated ExecutionThread class or NULL if not existant. 00061 ExecutionThread *execthread; 00062 00063 TNode() : LinkedListBase<TNode>() { thread=NULL; execthread=NULL; } 00064 ~TNode() {} 00065 }; 00066 00069 static inline void unregister(ExecutionThread *et) 00070 { kernel->_unregister(et); } 00071 private: 00073 GPrivate *phook; 00074 00076 RecursiveMutex mutex; 00077 00079 LinkedList<TNode> threadlist; 00081 int nrunning; 00082 00084 static void PhookNotifier(gpointer ptr); 00085 void _PhookNotifier(gpointer ptr); 00086 00088 static void *ThreadFuncWrapper(void *ptr); 00089 void *_ThreadFuncWrapper(void *ptr); 00090 00092 void _unregister(ExecutionThread *et); 00093 int _NRunningThreads(); 00094 00096 ThreadKernel(const ThreadKernel &); 00097 void operator=(const ThreadKernel &); 00100 ThreadKernel(); 00101 public: 00102 ~ThreadKernel(); 00103 00109 static void init(); 00110 00120 static void cleanup(); 00121 00130 inline static int NRunningThreads() 00131 { return(kernel ? kernel->_NRunningThreads() : -1); } 00132 }; 00133 00134 00158 class ExecutionThread 00159 { 00160 friend class ThreadKernel; 00161 private: 00165 ThreadKernel::TNode *handle; 00166 00168 ExecutionThread(const ExecutionThread &); 00169 void operator=(const ExecutionThread &); 00170 protected: 00173 virtual void run(); 00174 00177 void exit(); 00178 00182 void yield(); 00183 00184 public: 00186 ExecutionThread(); 00190 virtual ~ExecutionThread(); 00191 00210 int start(); 00211 00218 inline bool running() 00219 { return(g_atomic_pointer_get(&handle)); } 00220 }; 00221 00222 00223 #endif /* _ThreadLibrary_Thread_H_ */