Hi folks, I'm trying to implement threads in a simple SDL demo. As I understand it, a function in SDL can only be threaded if: (1) The function returns an int and (2) accepts a NULL pointer.
The function I'm trying to threadify already accepts a pointer to an array of tiles which I'm using to make up a game screen. My question therefore is, how is it possible to make this function a thread?
The function in question will control the movement of an enemy sprite across a tiled background.
I've tried the following:
int enemyMove(void *ptr);
And then in main() I'm creating the thread as follows:
thread = SDL_CreateThread(enemyMove, NULL);
But, my enemyMoves() function also needs to accept a pointer to an array called tiles, so ideally I'll need to do the following:
int enemyMove (Tile *tiles[], void *ptr );
However, on trying to compile this, I get a linker error, specficially, "LNK2019: unresolved external symbol".
The void pointer is meant to be any user data you want passed to the function. In this case you would pass 'tiles' as your void pointer to get it to the function.
One way to do it is like this:
1 2 3 4 5 6 7 8 9
int enemyMove(void* ptr)
{
Tile** tiles = reinterpret_cast<Tile**>(ptr);
//...
}
// then create the thread with this:
thread = SDL_CreateThread(enemyMove, tiles); // tiles, not NULL
The enemyMove() function is a member function of a class called Dot.
It can't be a member function. member functions have an additional, hidden 'this' parameter that makes them incompatible. The function has to be global. The only way to make it a member function would be if the member function is static.
Excellent, thank you. This is all starting to make sense. I'll be back at my desk in the morning so will make this function global and see how I get on. I'll let you know tomorrow!
Hello Disch, thanks for your efforts yesterday. Sadly I still haven't been able to get it working - after implementing your suggestions, i.e. making the required function global, I'm now grappling with an Unknown Exception error in Visual Studio, no doubt caused by an errant pointer somewhere in the code. I guess it's just a question of trawling through the program now and trying to track it down. Thanks again though for your help.