Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Pass data to a thread function  (Read 2045 times)

0 Members and 1 Guest are viewing this topic.

Contadotempo

  • Full Member
  • ***
  • Posts: 167
  • Firelink Shrine
    • View Profile
Pass data to a thread function
« on: October 02, 2010, 04:19:34 am »
Hi, I have a simple question about passing a variable to a thread function that I think it's easy to answer.

I was following this tutorial:
http://www.sfml-dev.org/tutorials/1.6/system-threads.php
And I read the part that explains my question, however I'm not having success when I try to pass a variable to the thread function.


I have the variable int n declared on the main, where n's value is 5.
Now I want to pass this value to a threaded function.
I tried the following:

Code: [Select]

void print_Console(void *UserData)
{
int* n = static_cast<int*>(UserData);
cout << "n=" << *n << endl;
}

int main()
{
int n=2; //EDITED AT Sat Oct 02, 2010 11:50 am
Thread th1(&print_Console, &n);
th1.Launch();
}



But it's not outputting n correctly.
So, what could be wrong here?

Thanks in advance

Lupinius

  • Jr. Member
  • **
  • Posts: 85
    • View Profile
Pass data to a thread function
« Reply #1 on: October 02, 2010, 01:30:45 pm »
It does actually output the right value for n. You just haven't assigned any value to n, so you get garbage.

Contadotempo

  • Full Member
  • ***
  • Posts: 167
  • Firelink Shrine
    • View Profile
Pass data to a thread function
« Reply #2 on: October 02, 2010, 01:50:36 pm »
Quote from: "Lupinius"
It does actually output the right value for n. You just haven't assigned any value to n, so you get garbage.

Oh sorry, I did do int n=2; on the compiler. I forgot to post it here since I wrote the example from scratch.
It still displays garbage for some reason.

EDIT: Hum, strange. I tried it on a new empty project and now it DOES display n correctly. Not sure why, or what made this happen, but at least it's fixed. But if I try it on the old project it still prints stuff like "0034EDDC", "0045EF9C". Guess I'll stick with a new project. Thanks, for the input.

 

anything