//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++编译运行通过
//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++编译运行通过