Passing variables to threads?

Started by
3 comments, last by Rasmadrak 17 years, 9 months ago
Just a question regarding threads: I was up all night programming an A'star non-tilebased pathfinding (not completely done yet) but I cannot for the life of me figure out how to supply threads with variables...

1) Unit wants pathfinding to A from B, and storing the path in it's stl list "Waypoints".

2) FindPath(A,B,Unit.Waypoints);

3) FindPath(vector3d Start, vector3d End, list<node> &Path)
 { 
 //do preparations here...
 //...
 //then:

 LaunchThread(Start,End,Path);
 }
How can I supply the thread with variables..? I havn't used threads that much (at all, more or less). Also, returning values with threads... how can this be done?
"Game Maker For Life, probably never professional thou." =)
Advertisement
What threading library are you using? Different threading systems use different mechanisms to pass arguments.
I'm using WINAPI, standard thread creation...

DWORD PathThread;DWORD WINAPI ThreadFunc(LPVOID pvParam) { //... Code here. };    PathThread =  CreateThread(0,                             0,                             ThreadFunc,                             0,                             0,                             NULL);


...or something similar.


But since I have very limited knowledge about threads, and that I'm at work now - I can't really paste the actual code. It is similar as above thou.
"Game Maker For Life, probably never professional thou." =)
To pass arguments to a thread function with the Win32 threading API, you generally aggregate the arguments into a structure and pass a pointer to that structure as the void pointer argument for thread creation. In the function that you use as an argument for the thread you then cast that void pointer back to the struct type and access the members. Ex:
struct Arguments {  int arg1;  int arg2;  std::string arg3;};DWORD WINAPI ThreadFunc(LPVOID arg_struct) {  Arguments * args = reinterpret_cast<Arguments *>(arg_struct);  // do stuff}// somewhere elseArguments args = { 0, 5, "Moo! Moo, I say!" };CreateThread(0, 0, &ThreadFunc, &args, 0, 0);
This seems to be exactly what I want!

Some smaller redesigning of the pathfinding class will be needed, but that´s no problem - I think it will only improve it's flexibility!

something like:
struct PathFind{bool Done;node Start,End, Path;FindPath(...);};class unit : public PathFind{//...};


Thank you for your help!!

/Robert
"Game Maker For Life, probably never professional thou." =)

This topic is closed to new replies.

Advertisement