C++ pthread

//header
//thread.h

#ifndef THREAD_H
#define THREAD_H

#include <iostream>
using namespace std;

class Thread
{
public:
    Thread();
    int Start(void *arg);
protected:
    int Run(void *arg);
    static void* EntryPoint(void *);
    virtual void Setup();
    virtual void Execute(void *);
    void *Arg() const;
    void Arg(void *a);
private:
    pthread_t PthreadId_;
    void *Arg_;
};

#endif // THREAD_H

//-------------------------------------------//
//cpp
//thread.cpp
#include "thread.h"

Thread::Thread()
{}

int Thread::Start(void *arg)
{
    Arg(arg); //store user data
    int code = pthread_create(&PthreadId_,NULL,Thread::EntryPoint,arg);
    return code;
}

int Thread::Run(void *arg)
{
    Setup();
    //Execute(arg);
    return 1;
}

//*static*/
void * Thread::EntryPoint(void *pthis)
{
    Thread *pt = (Thread *)pthis;
    pt->Run(pt->Arg());
    delete pt;
    return (NULL);
}

void Thread::Setup()
{
    while(1)
    {
        printf("this is in Setup()/n");
        sleep(1);
    }
}

void Thread::Execute(void *arg)
{}

void * Thread::Arg() const
{
    return Arg_;
}

void Thread::Arg(void *a)
{
    Arg_ = a;
}

//
//main.cpp
#include "thread.h"

int main(int argc, char ** argv)
{
      printf("-------------------------hello/n");
    Thread *tt = new Thread;

    if((tt->Start(tt))!=0)
    {
        printf("setup pthread error/n");
        exit(1);
    }
    while(1)
    {
        printf("------------------------this is in main()/n");
        sleep(2);
    }
    return EXIT_SUCCESS;
}

// g++ -o pt thread.cpp main.cpp -lpthread
//本例子经过调试在cygwin3.4下的g++编译运行通过
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值