Friday, 15 September 2006

Redo from start - Multithreading in C++ && OO

The Win32 API for threading have been designed for C, therefore they don't fit very well the use inside classes. In highest-level languages (such as Java), threading is implementable simply extending the Thread class and overriding the run() method. In C++, things are slighly more complex, expecially because it is impossible to reach classes methods from an isolated static function.

So, it is necessary... once again... pull up socks and use the _beginthreadex API.

class Threader

  // this is the method called by main
  static unsigned __stdcall ThreadStaticEntryPoint(void * pThis)
    Threader * pthX = (Threader *) pThis;
    pthX -> EntryPoint();

  // this is the real thread method
  void EntryPoint()
    // put thread's job here

int main() {

  unsigned int uiThread1ID;

  // let's call thread. the NULL are useful parameters, but not obbligatory
  HANDLE hth1 = (HANDLE)_beginthreadex( NULL, 0, Threader::ThreadStaticEntryPoint, NULL, NULL, &uiThread1ID );


You can find an excellent and more extended explanation on Code Project.

Don't forget to include process.h!

No comments: