Thursday 17 September 2009

Arbitrarily turn static functions into individual threads

There's a lot of routines that are supposed to run "behind the scene", accomplishing repetitive and constant taks. For instance, in 3D engine the movements should be time-based, so that things behave the same way indipendently from the underlying architecture. We could define a class that "checks the clock" and computes the "amount of changes" to do in the scene. Our observers - that is a geometry transformers or a physic routine - simply "emphasize" their values proportionally to the elapsed time.

The best way for keeping "background duties classes" and the main engine separate is the use of threads. I already used them in the past, but in a statical way. This time, I wanted some kind of "abstract thread converter" which takes a pointer to a static function and turns it into a thread on its own.

Here comes some brief snippet. First of all, I defined a PLTthread class:

class PLTthread {
public:
  // empty constructor 
  PLTthread() {};
  // links the specified function, using specified  parameters
  void LinkFunction(static DWORD WINAPI fun, void* dwThrdParam = 0); 
private:
  // handler for the created thread
  HANDLE ThreadHandler;
  // thread ID
  DWORD dwThreadId;
}
Many additional methods could be created for handling thread's execution, but I wanna keep this example straightforward: you'll just pass a static method and it will start on its own. The actual code:

void PLTthread::LinkFunction(static DWORD WINAPI fun, void* dwThrdParam) {
    this->ThreadHandler = CreateThread(NULL, 0,
                            (LPTHREAD_START_ROUTINE)fun, &dwThrdParam,
                            0, &this->dwThreadId);  
    }
That's it. Now you can instantiate a PLTthread class and send it your function, casting it as DWORD.

Threads are a bit tricky, MFC are a pain in the ass; everything is a complete mess if you use to think object oriented. But this facility helps me a lot.

1 comment:

Anonymous said...
This comment has been removed by a blog administrator.