Class thread function

So, I have a class with one function - update

Inside update, I create a thread and I give pointer to stream data. What I want to do is to make thread function a part of class, but I am having a lil problems with syntax.

How I create thread
1
2
3
4
5
6
7
8
9
10
void Server::createThread(int slot)
{
	hThreadArray[slot] = CreateThread( 
    NULL,                   // default security attributes
    0,                      // use default stack size  
    streamData,       // thread function name
    (void *)&client[slot],          // argument to thread function 
    0,                      // use default creation flags 
    NULL);   // returns the thread identifier 
}


My thread function
1
2
3
4
5
6
DWORD  WINAPI streamData(void *data )
{
	printf("Inside thread\n");
	return 0;

}


So, how do I make it as a part of class? The main reason for it is so could my thread share same data of a class, so don't worry about sending structs to thread.
I'm not an expert on this, but I don't think you can. CreateThread() expects a function with a certain signature; namely, it returns a DWORD uses the WINAPI calling convention and takes a single void* as a parameter. Making a function like that a method would change the signature because of the implied "this" pointer it would need to take.
Make the thread function static and pass this as the argument. You can then cast your data pointer back to an instance of your class from within your thread function and viola, you have access to your class members.

e.g.
1
2
3
4
5
6
7
8
9
10
void Server::createThread(int slot)
{
	hThreadArray[slot] = CreateThread( 
    NULL,                   // default security attributes
    0,                      // use default stack size  
    streamData,       // thread function name
    (void *)this,          // argument to thread function 
    0,                      // use default creation flags 
    NULL);   // returns the thread identifier 
}


Your thread function:

1
2
3
4
5
6
7
8
9
10
11
12
13
// Declared as
class Server {
public:
static DWORD WINAPI streamData(void *data);
...
};

// And it's implementation
DWORD WINAPI Server::streamData(void *data)
{
        Server* server = static_cast<Server*>(data);
        return (server->DoStuff());  // Call a member function to do your work
}


Edit - Don't forget about thread safety though!
Last edited on
Topic archived. No new replies allowed.