I implemented a simple c++ thread wrapper; it works in Linux, but fails in
BSD.
Here is the code. The idea is that an other class will inherit and implement the virtual methods Setup and Execute. The thread is created in Start,
pthread_create returns 0 indicating that no error occured, the pthread_t variable is set. But the code found in Setup and Execute is never run.
Thanks, in advance
.h
Code:
Expand|Select|Wrap|Line Numbers
- class OC_Thread
- {
- public:
- OC_Thread();
- virtual ~OC_Thread();
- int Start(void * arg);
- int Join();
- protected:
- int Run(void * arg);
- int Sleep(unsigned int time);
- static void * EntryPoint(void*);
- virtual void Setup(){};
- virtual void Execute(void*){};
- void * Arg() const {return Arg_;}
- void Arg(void* a){Arg_ = a;}
- private:
- pthread_t m_thread_id;
- void * Arg_;
- bool m_joinable;
- };
Code:
Expand|Select|Wrap|Line Numbers
- #include "Thread.h"
- //extern "C" void* thread_func(void*)
- //{
- // printf("Hey from thread funv\n");
- //}
- OC_Thread::OC_Thread()
- {
- printf("Hey from My OC_Thread\n");
- }
- OC_Thread::~OC_Thread()
- {
- printf("delete from OC_Thread\n");
- if (m_joinable)
- {
- pthread_detach(m_thread_id);
- }
- }
- int OC_Thread::Start(void * arg)
- {
- Arg(arg); // store user data
- int code =0;
- code = pthread_create(&m_thread_id, NULL, OC_Thread::EntryPoint, (void*)this);
- printf("Hey from start code is %d and id is %d\n", code, (int)m_thread_id);
- return code;
- }
- int OC_Thread::Run(void * arg)
- {
- printf("Hey from run\n");
- Setup();
- Execute( arg );
- return 0;
- }
- int OC_Thread::Sleep(unsigned int time)
- {
- sleep(time);
- return 0;
- }
- int OC_Thread::Join()
- {
- void *res;
- pthread_join(m_thread_id, &res );
- return 0;
- }
- /*static */
- void* OC_Thread::EntryPoint(void * pthis)
- {
- printf("Hey from EntryPoint\n");
- fflush(stdout);
- OC_Thread* pt = (OC_Thread*)pthis;
- pt->Run( pt->Arg() );
- return NULL;
- }