关闭

跨平台的线程封装类

标签: C++多线程跨平台
741人阅读 评论(0) 收藏 举报
分类:
#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
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;
}
封装了一个线程基类,可以在windows和linux下使用,其中run方法是要求继承的子类必须实现的,这个方法相当于线程函数,可以看到,在基类base_thread中,我在线程函数中调用了方法run。wait是用来等待线程安全退出放在主线程中卡住等待的。
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场