something of my own...
For windows there's the WaitForSingleObject function..
for linux.. I asked that question like.. 4 days ago, and CodePlug told me to use the pthread_cleanup_push... which basicly I emulated...
This code is incomplete.. only serves as example.
First there's the header then the body
Code:
#ifdef WIN32
#include<windows.h>
typedef DWORD THREADRETTYPE;
typedef DWORD pthread_t;
typedef struct _THREAD_ATTRS{
int n_refs;
pthread_t thread_id;
HANDLE hwthread;
DWORD (WINAPI *func)(void*);
} THREAD_ATTRS;
#else
#include <pthread.h>
#define WINAPI
typedef struct _THREAD_ATTRS{
int n_refs;
pthread_t thread_id;
void* (*func)(void*);
bool ended;
} THREAD_ATTRS;
typedef void* THREADRETTYPE;
#endif
typedef THREADRETTYPE (WINAPI *THREADCALLBACKFUNC)(void*);
class Thread{
private:
#ifndef WIN32
friend void* pthread_entry_func(void*);
#endif
THREAD_ATTRS *attrs;
public:
Thread(THREADCALLBACKFUNC = NULL);
Thread(const Thread&);
~Thread();
Thread& operator=(const Thread&);
pthread_t id();
bool run(void *args);
bool isRunning();
bool hasExited();
bool waitExit(THREADRETTYPE* retval=NULL);
bool terminate();
};
and the cpp you need
Code:
#ifndef WIN32
struct pthread_args{
Thread *thread;
void *args;
void *(*f)(void*);
};
void* pthread_entry_func(void* args){
pthread_args* p = (pthread_args*)args;
Thread& t = *p->thread;
THREADCALLBACKFUNC f = p->f;
void *params = p->args;
delete p;
if(t.attrs) t.attrs->ended=false;
void *res=NULL;
try{
res = f(params);
}catch(...){
if(t.attrs) t.attrs->ended=true;
throw;
}
if(t.attrs) t.attrs->ended=true;
return res;
}
#endif
bool Thread::run(void *args){
assert(attrs != NULL);
if(isRunning() || attrs->func == NULL )
return false;
#ifdef WIN32
attrs->hwthread = CreateThread(NULL,0,attrs->func,args,0,&attrs->thread_id);
return attrs->hwthread!=NULL;
#else
pthread_args *p = new pthread_args;
p->thread=this;
p->f=attrs->func;
p->args=args;
return pthread_create(&attrs->thread_id,NULL,pthread_entry_func,p) == 0;
#endif
}
bool Thread::hasExited(){
if(attrs == NULL) return true;
#ifdef WIN32
bool res = WaitForSingleObject(attrs->hwthread,0) == WAIT_OBJECT_0;
#else
bool res = attrs->ended;
#endif
if(res)
clean_THREAD_ATTRS(attrs);
return res;
}
bool Thread::terminate(){
#ifdef WIN32
bool ret = TerminateThread(attrs->hwthread,1)==TRUE;
#else
bool ret = pthread_cancel(attrs->thread_id)==0;
#endif
clean_THREAD_ATTRS(attrs);
return ret;
}