以封装一个线程类为例
Thread (一个线程抽象基类) |
---|
threadId: pthread_t |
Strat(): void |
Join(): void |
ThreadRoutine(void* arg): void |
Run(): void(纯虚函数) |
Run()表示这个线程类的执行体,每个线程类都可能不一样
TestThread : Thread (派生自 THread 的一个具体类) |
---|
threadId: pthread_t |
Strat(): void |
Join(): void |
ThreadRoutine(void* arg): void |
Run(): void |
* Thread.h
#ifndef _THREAD_H_
#define _THREAD_H_
class Thread
{
public:
Thread();
virtual ~Thread() = 0;
void Start();
void Join();
static void* (*Thread_routine)(void *arg);
private:
virtual void Run() = 0;
pthread_t threadId_;
};
- Thread.c
#include "Thread.h"
#include <iostream>
using namespace std;
Thread::Thread()
{
cout << "Thread..." << endl;
}
Thread::~Thread()
{
cout << "~Thread..." << endl;
}
Thread::Start()
{
pthread_create(&threadId_, NULL, Thread_routine, this);
}
Threa::Join()
{
pthread_join(threadId_);
}
Thread::Thread_routine(void *arg)
{
Thread* thread = static_cast<Thread*>(arg);
Thread->Run();
return NULL;
}
- main.c
#include "Thread.h"
class TestThread : public Thread
{
public:
TestThread(int count) : count_(count)
{
cout << "TestThread..." << end;
}
~TestThread()
{
cout << "~TestThread..." << end;
}
void Run()
{
while(count_--)
{
cout << "this is a test..." << endl;
sleep(1);
}
}
int count_;
}
int main()
{
TestThread t(5);
t.start();
t.Join();
return 0;
}