views:

52

answers:

2

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

+1  A: 

Usually you specify the address of the object of myclass as arg type and cast it inside the ThreadProc. But then you'll be blocked on how passing the int argument.

void ThreadProc(void *arg)
{
   myclass* obj = reinterpret_cast<myclass*>(arg);
   //Can't do this
   obj->SetNumber(???);
}

As you said this is maybe not only a bit slow but it also clutters the code. I would suggest to use boost::bind for argument binding and to create the threads in an os independent way (for your own source at least) you could use boost::thread. Then no need for static methods for your threads.

Now in the C++0x standard, here a small tutorial

jdehaan
I'm not using boost
Milo
oh ok, well I'll just pass a struct then where 1 of its members is the self pointer
Milo
yes that could be a solution if you're really against boost usage. Note however that these things are now part of the new C++0x standard supported by major compilers, so it's not exotic to use. They are in a different namespace thought: std instead of boost
jdehaan
A: 

I would suggest you to make a friendly class with a static method for this purpose. It looks much cleaner. Eg:-

class FriendClass
{
public:
  static void staticPublicFunc(void* );
};

Now befriend the above class in your main class ...

class MyClass
{
  friend void FriendClass::staticPublicFunc(void*);
};

This should enable you to set the friend-function as the thread-function and access the class per instance in each thread. Make sure to synchronize your access to data visible across threads.

Abhay