📄 thread.h
字号:
#ifndef UTILS_BASE_THREAD_H_#define UTILS_BASE_THREAD_H_#include <algorithm>#include <list>#include <vector>#ifdef POSIX#include <pthread.h>#endif#include "messagequeue.h"#ifdef WIN32#include "win32.h"#endifnamespace utils_base {class Thread;class ThreadManager {public: ThreadManager(); ~ThreadManager(); static Thread *CurrentThread(); static void SetCurrent(Thread *thread); void Add(Thread *thread); void Remove(Thread *thread);private: Thread *main_thread_; std::vector<Thread *> threads_; CriticalSection crit_;#ifdef POSIX static pthread_key_t key_; #endif#ifdef WIN32 static DWORD key_;#endif};class Thread;struct _SendMessage { _SendMessage() {} Thread *thread; Message msg; bool *ready;};enum ThreadPriority { PRIORITY_NORMAL, PRIORITY_IDLE,};class Thread : public MessageQueue {public: Thread(SocketServer* ss = 0); virtual ~Thread(); static inline Thread* Current() { return ThreadManager::CurrentThread(); } inline bool IsCurrent() const { return (ThreadManager::CurrentThread() == this); } void SetPriority(ThreadPriority priority) { priority_ = priority; } virtual void Start(); virtual void Stop(); // By default, Thread::Run() calls ProcessMessages(kForever). To do other // work, override Run(). To receive and dispatch messages, call // ProcessMessages occasionally. virtual void Run(); virtual void Send(MessageHandler *phandler, uint32 id = 0, MessageData *pdata = NULL); // From MessageQueue virtual void Clear(MessageHandler *phandler, uint32 id = (uint32)-1); virtual void ReceiveSends(); // ProcessMessages will process I/O and dispatch messages until: // 1) cms milliseconds have elapsed (returns true) // 2) Stop() is called (returns false) bool ProcessMessages(int cms);#ifdef WIN32 HANDLE GetHandle() { return thread_; }#endifprivate: static void *PreRun(void *pv); void Join(); std::list<_SendMessage> sendlist_; ThreadPriority priority_; bool started_; bool has_sends_;#ifdef POSIX pthread_t thread_;#endif#ifdef WIN32 HANDLE thread_;#endif friend class ThreadManager;};// AutoThread automatically installs itself at construction// uninstalls at destruction, if a Thread object is// _not already_ associated with the current OS thread.class AutoThread : public Thread {public: AutoThread(SocketServer* ss = 0); virtual ~AutoThread();};} // namespace utils_base#endif // UTILS_BASE_THREAD_H_
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -