that will encapsulate the threading mechanism. Certain aspects of thread programming, like mutexes and
semaphores are not discussed here. Also, operating system calls to manipulate threads are shown in a generic
form.
Brief Introduction To Threads
To understand threads one must think of several programs running at once. Imagine further that all these
programs have access to the same set of global variables and function calls. Each of these programs would
represent a thread of execution and is thus called a thread. The important differentiation is that each thread
does not have to wait for any other thread to proceed. All the threads proceed simultaneously. To use a
metaphor, they are like runners in a race, no runner waits for another runner. They all proceed at their own
rate.
Running Codes
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 {return Arg_;}
void Arg(void* a){Arg_ = a;}
private:
THREADID ThreadId_;
void * Arg_;
};
Thread::Thread() {}
int Thread::Start(void * arg)
{
Arg(arg); // store user data
int code = thread_create(Thread::EntryPoint, this, & ThreadId_);
return code;
}
int Thread::Run(void * arg)
{
Setup();
Execute( arg );
}
/*static */
void * Thread::EntryPoint(void * pthis)
{
Thread * pt = (Thread*)pthis;
pthis−>Run( Arg() );
}
virtual void Thread::Setup()
{
// Do any setup here
}
virtual void Thread::Execute(void* arg)
{
// Your code goes here
}
{
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 {return Arg_;}
void Arg(void* a){Arg_ = a;}
private:
THREADID ThreadId_;
void * Arg_;
};
Thread::Thread() {}
int Thread::Start(void * arg)
{
Arg(arg); // store user data
int code = thread_create(Thread::EntryPoint, this, & ThreadId_);
return code;
}
int Thread::Run(void * arg)
{
Setup();
Execute( arg );
}
/*static */
void * Thread::EntryPoint(void * pthis)
{
Thread * pt = (Thread*)pthis;
pthis−>Run( Arg() );
}
virtual void Thread::Setup()
{
// Do any setup here
}
virtual void Thread::Execute(void* arg)
{
// Your code goes here
}
No comments:
Post a Comment