Creating a Thread with a method as a startproc

Discussion in 'Forum for discussion of ANTICHAT' started by Dracula4ever, 6 Jun 2006.

  1. Dracula4ever

    Dracula4ever Elder - Старейшина

    Joined:
    8 May 2006
    Messages:
    418
    Likes Received:
    183
    Reputations:
    26
    Here is something I've picked up while trying to open a new thread for a method, and not a function

    CreateThread only accepts a ThreadProc (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/threadproc.asp) as a start routine. of course, specifying object.method as a start routine won't work, a call to a method is not the same as to a function...
    But, a call to a static function is very much like it, so we just make our method static and we can specify it as parameter for CreateThread

    "What's the point using a static method, I have lost all my object properties"
    well, here is another trick, you can literally "fake" the 'this' pointer and you can get all your nonstatic properties and methods

    how do you do that, simple, the CreateThread function allows you to pass one parameter to the start routine, so you can pass the object in hand and get back all the data you 'lost'

    In case all of this is a bit mixed up, here is an example:
    //'Start' would be the trigger for the new thread that will run on 'bar':
    class foo{
    private:
    int a=0;
    static DWORD WINAPI bar(LPVOID lpParam){
    foo *_this=(foo *)lpParam; //We can do this because we know that the param is always a foo instance

    //now we can use _this as our 'this' the same way
    cout << _this->a << endl;
    return 0;
    }
    public:
    void Start(){
    int thread_id;
    CreateThread(NULL, 0,
    this->listen_thread, //We CAN send here a static method, we CANNOT send a nonstatic one
    this, //In order to later fake 'this'
    0, &thread_id);
    }
    }


    enjoy!
    dracula4eever