- #ifdef WIN32
- #include <Windows.h>
- #include <process.h>
- #else
- #include <pthread.h>
- #endif
- /*
- #ifdef WIN32
- typedef unsigned INT (__stdcall *thread_func) (void*);
- #else
- typedef void* (*thread_func) (void*);
- #endif
- */
- Class Base_thread
- {
- Public
- Base_thread ();
- virtual ~base_thread ();
- bool Create ();
- void Wait ();
- virtual void run () = 0;
- #ifdef WIN32
- static unsigned __stdcall thread_func (void* Arg);
- #else
- static void* thread_func (void* Arg);
- #endif
- Protected
- #ifdef WIN32
- HANDLE M_handle;
- #else
- pthread_t m_thread_t;
- #endif
- };
- #endif
[CPP]View PlainCopy
- Base_thread::base_thread ()
- {
- #ifdef WIN32
- M_handle = NULL;
- #else
- m_thread_t = 0;
- #endif
- }
- Base_thread::~base_thread ()
- {
- #ifdef WIN32
- if (NULL! = m_handle)
- {
- CloseHandle (M_handle);
- }
- M_handle = NULL;
- #else
- m_thread_t = 0;
- #endif
- }
- BOOL Base_thread::create ()
- {
- BOOL ret = false;
- #ifdef WIN32
- M_handle = (handle) _beginthreadex (null, 0, Thread_func, this , 0, NULL);
- if (NULL! = m_handle)
- {
- ret = true;
- }
- #else
- if (0 = = Pthread_create (&m_thread_t, NULL, Thread_func, this ))
- {
- ret = true;
- }
- Else
- {
- m_thread_t = 0;
- }
- #endif
- return ret;
- }
- void Base_thread::wait ()
- {
- #ifdef WIN32
- WaitForSingleObject (M_handle, INFINITE);
- if (NULL! = m_handle)
- {
- CloseHandle (M_handle);
- }
- M_handle = NULL;
- #else
- Pthread_join (m_thread_t, NULL);
- m_thread_t = 0;
- #endif//WIN32
- }
- #ifdef WIN32
- unsigned __stdcall base_thread::thread_func (void* Arg)
- #else
- void* Base_thread::thread_func (void* Arg)
- #endif
- {
- Base_thread *pthis = (base_thread*) arg;
- Pthis->run ();
- return NULL;
- }
Encapsulates a line base class that can be used under Windows and Linux, where the Run method requires the inherited subclass to be implemented, which is equivalent to the thread function, as you can see, in the base class Base_thread, I call the method run in the thread function. Wait is used to wait for a thread-safe exit to stay stuck in the main thread.
Thread encapsulation classes for cross-platform (Win and Unix)