SFML community forums

Help => System => Topic started by: Chocolatesheep on December 17, 2011, 05:21:48 pm

Title: Passing variables to ThreadFunction()
Post by: Chocolatesheep on December 17, 2011, 05:21:48 pm
What if I need to pass a variable into the thread function? How can I do that? It's not explained in the tutorial on the SFML website. Two Sprite variables need to be passed into my thread function, so how do I declare that function?
WIll it be void ThreadFunction(sf::Sprite Sprite, sf::Sprite Sprite2);
I keep getting an error, and what is the void *UserData for?
And how do I later create the thread?
In the tutorial it just says:
sf::Thread Thread(&ThreadFunction)
?
Title: Passing variables to ThreadFunction()
Post by: Laurent on December 17, 2011, 05:33:18 pm
UserData is for passing extra data to the thread. It's a void*, so you can pass a pointer to anything -- but only one thing.

So basically you can do this for example:
Code: [Select]
void ThreadFunction(void* userData)
{
    sf::Sprite* sprites = static_cast<sf::Sprite*>(userData);
    ...
}

int main()
{
    sf::Sprites[2] sprites = {sprites1, sprites2};
    sf::Thread thread(&ThreadFunction, sprites);
    thread.Launch();
    return 0;
}