#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();
}