I have a function in my class that creates a thread and gives it arguments to call a function which is part of that class but since thread procs must be static, I can’t access any of the class’s members. How can this be done without using a bunch of static members in the cpp file to temporarily give the data to be manipulated, this seems slow.
Heres an example of what I mean:
in cpp file:
void myclass::SetNumber(int number)
{
numberfromclass = number;
}
void ThreadProc(void *arg)
{
//Can't do this
myclass::SetNumber((int)arg);
}
I can’t do that since SetNumber would have to be static, but I instance my class a lot so that won’t work.
What can I do?
Thanks
Usually you specify the address of the object of myclass as
argtype and cast it inside the ThreadProc. But then you’ll be blocked on how passing the int argument.As you said this is maybe not only a bit slow but it also clutters the code. I would suggest to use
boost::bindfor argument binding and to create the threads in an os independent way (for your own source at least) you could useboost::thread. Then no need for static methods for your threads.Now in the C++0x standard, here a small tutorial