Rss Feed

05 August 2010

Threads in C++

It is fairly simple to create, but difficult to debug due the complexity in multiple-threaded environments.

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).
  1. Create a base class (class Thread).
  2. Create the worker class (class A) and make it a subclass of
    the
    base class (cf. step 1).
  3. Create an instance of your worker class (cf. step 2) and
    call
    its start() method.

-- 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() { /* Do some work! */ }
// ...
}


Thread * p = new A();
if (p) p->start(); // Spawns it in a new thread
-- snip --