[GNU/Linux]线程的面向对象封装

Thread.h

#ifndef _THREAD_H
#define _THREAD_H

#include <pthread.h>
#include <unistd.h>
#include <time.h>

class Thread
{
public:
    Thread();
    virtual ~Thread();

    // 创建并启动
    virtual int Run();

    // 等待和收回资源
    static void Join(Thread* thrd);

    // Sleep函数
    static void Msleep(int ms);
    static void Sleep(int s);

public:
    virtual int Routine() = 0;

private:
    pthread_t hThread;
};






#endif

Thread.cpp

#include <stdio.h>
#include "Thread.h"

Thread::Thread() 
{
}

Thread::~Thread()
{
}

static void* Thread_Proc_Linux(void* param)
{
    Thread* thrd = (Thread*) param;
    thrd->Routine();
    return NULL;
}

int Thread::Run()
{
    // 创建线程
    if(pthread_create(&hThread, NULL, 
        Thread_Proc_Linux, this) < 0)
    {
        return -1;
    }

    return 0;
}

void Thread::Join(Thread* th)
{
    pthread_join(th->hThread, NULL);
}

void Thread::Msleep(int ms)
{
    timespec ts;
    ts.tv_sec = ms / 1000;
    ts.tv_nsec = (ms % 1000) * 1000000;
    nanosleep(&ts, NULL);
}

void Thread::Sleep(int s)
{
    sleep(s);
}

 

main.cpp

#include <stdio.h>

#include "Thread.h"

class MyTask : public Thread
{
public:
    virtual int Routine()
    {
        for(int i=0; i<10; i++)
        {
            printf("MyTask: %d \n", i);
            Thread::Sleep(1);
        }
        return 0;
    }
};
// 
int main()
{
    MyTask t;
    t.Run();
    
    Thread::Join(&t);	
    printf("main exit.\n");
    return 0;
}

 

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注