线程

#include <pthread.h>
using namespace std;

#pragma comment(lib, "pthreadVC2.lib")


class SwyThread
{
public:
	SwyThread(bool joinable = true)
		: m_joinable(joinable)
	{
		memset(&m_thread, 0, sizeof(m_thread));
	}
	virtual ~SwyThread() {}
private:
	DISALLOW_COPY_AND_ASSIGN(SwyThread);// 默认拷贝构造函数设为private 禁用

public:
	int start()
	{
		int err = pthread_create(&m_thread, NULL, SwyThread::threadEntry, this);
		return err;
	}
	void join()
	{
		//joinable状态 完了后自己pthread_join下
		pthread_join(m_thread, NULL);
	}
	inline bool joinable()
	{
		return m_joinable;
	}

protected:
	virtual void run() {}

private:
	static void* threadEntry(void* param);

private:
	bool m_joinable;
	pthread_t m_thread;
};

void* SwyThread::threadEntry(void* param)
{
	SwyThread* pthread = static_cast<SwyThread*>(param);
	if (pthread != NULL)
	{
		if (!pthread->joinable())
		{
			//unjoinable则退出会自己释放
			pthread_detach(pthread_self());//状态改为unjoinable 确保资源的释放
		}			
		pthread->run();
	}
	else
	{
		//自己分离自己 pthread_self就是自己的线程id
		pthread_detach(pthread_self());
	}
	return NULL;
}

class TaskA :public SwyThread
{
public:
	TaskA(int n) { name = n; }
	~TaskA() {}
protected:
	virtual void run();
public:
	void stopThread()
	{
		m_running = false;
		join();
		//linux线程和 windows不同 pthread状态有 joinable和unjoinable
		//如果joinable线程退出或者pthread_exit,自己不会释放占用的堆栈和线程描述符(8k多空间)
		//只有当调用了pthread_join后这些资源才释放
	}
private:
	bool m_running;
	int name;
};
void TaskA::run()
{
	m_running = true;
	int i = 0;
	while (m_running)
	{
		cout << "i am " << name << endl;
		Sleep(1000);
		if (i++ > name)
			stopThread();
	}
}

int main()
{

	TaskA* a = new TaskA(8);
	TaskA* b = new TaskA(15);
	a->start();
	b->start();
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值