Threads in C++ ...
... is fairly simple.
Threads in C++ can be done by a simple and workable 3-step approach. Doing it in the right way will make it equivalent to i.e. the Java-approach, where you have to either inherit from a class (java.lang.Thread) or implement an interface (java.lang.Runnable).
-- snip --
class Thread {
static DWORD WINAPI ThreadFunc(LPVOID pv) {
try { (reinterpret_cast<Thread*>(pv))->run(); }
catch(...) { }
return 0;
}
public:
typedef DWORD threadid;
virtual void run() = 0;
void start() {
threadid id;
::CreateThread(NULL, 0, ThreadFunc, this, 0, &id);
}
//...
}
};
class A : public Thread {
virtual void run() { /* To Do */ }
// ...
}
Threads in C++ can be done by a simple and workable 3-step approach. Doing it in the right way will make it equivalent to i.e. the Java-approach, where you have to either inherit from a class (java.lang.Thread) or implement an interface (java.lang.Runnable).
- Create a base class, that you might call "Thread". This class will be equivalent to the java.lang.Thread class.
- Class A (your custom worker class) must inherit from the Thread class (cf. step 1).
- Create an instance of your class A and call its start() method.
-- snip --
class Thread {
static DWORD WINAPI ThreadFunc(LPVOID pv) {
try { (reinterpret_cast<Thread*>
catch(...) { }
return 0;
}
typedef DWORD threadid;
virtual void run() = 0;
void start() {
threadid id;
::CreateThread(NULL, 0, ThreadFunc, this, 0, &id);
}
//...
}
};
class A : public Thread {
virtual void run() { /* To Do */ }
// ...
}
Thread * p = new A();
if (p) p->start(); // Spawns it in a new thread
-- snip --


0 Comments:
Post a Comment
Links to this post:
Create a Link
<< Home