跨平台的线程封装类

#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是用来等待线程安全退出放在主线程中卡住等待的。
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值