C++ pthread

来源:互联网 发布:2016网络彩票代理加盟 编辑:程序博客网 时间:2024/05/19 17:24
//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++编译运行通过
原创粉丝点击