Thursday, July 9, 2009

C++ Win Api Threading (Advanced)?

Herro, I was playing with a little win api thread this morning, and saw that you cant call a function from the thread creating with PARAMS ? Dang, well heres a snip of the source :





HANDLE wThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) walkx, 0, 0, 0);





Basically, what I would LOVE to do is call it like this :





HANDLE wThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) walkx(X COORD, Y COORED), 0, 0, 0);





Buuuut of course I cant ;)





So, really in search of some help / possible solutions / other things I could be doing with my time, thanks ! ^^





Oh, and yeah I already checked out some other people sources, MSDN, and the like.

C++ Win Api Threading (Advanced)?
Yeah, I hear you. Wish I could too. This is how I do it...








In the header file:





class phoo : public basephoo


{


......


INT x_coord;


INT y_coord;





private:


CWinThread* handMyThread;


static UINT MyThread( LPVOID pParam );





}





Now in the cpp file some initializer launches the thread:





handMyThread = AfxBeginThread( MyThread, this, THREAD_PRIORITY_NORMAL, 0, 0, NULL ); // choose your priority.





then:





UNIT phoo::MyThead( LPVOID pParam )


{


phoo* myPhooPtr = (phoo*)pParam; // DO FIRST !!! This is your reference back to phoo.





// now we can use x and y





INT xPlusy = myPhooPtr-%26gt;x_coord + myPhooPtr-%26gt;y_coord;





...................


return 0;


}





Remember that when you start using threads, you may want to start using CMutex objects to protect your data--especially if x_coord and y_coord are changing.





Hope that helps.
Reply:The argument to CreateThread() that's just after the function you want to call is supposed to be used to hold a pointer to the data you want to pass to the function.





So you'd create a struct to hold the parameters to pass, then pass the address of that struct to CreateThread(), like so:





struct coords


{


int x;


int y;


} p;





p.x=12;


p.y=34;





CreateThread(NULL,0,walkx, %26amp;p, 0,0);


No comments:

Post a Comment