Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi,

How to make a thread procedure to access non-static member variables? Plaese give me a detial example..

Thanks,
Laje...
Posted
Comments
Sergey Alexandrovich Kryukov 20-Jan-11 23:04pm    
No difference between static and non-static -- at all, and no problems. Both ways need synchronization.

1 solution

1 of the parameters to creating the thread is User Data. Pass in your class instance as the User Data.
I find that the easiest way is to call a non-static function from the static function if I need to access variables more than a few times.

//Create the thread
m_hThread = CreateThread(NULL, 0, &ThreadProc, this, 0, NULL);

//The static member function for the callback
DWORD WINAPI MyClass::ThreadProc(void *pInst) {
	return ((MyClass *)pInst)->ThreadProcInternal();
}

//Non-static member function to use as normal
DWORD MyClass::ThreadProcInternal() {
	m_nMyNumber = 0; //for eg.
}


EDIT:
This example uses Win32 Threads, but the principal is the same for all thread implementations like pthreads. They all take a user defined parameter.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 20-Jan-11 23:15pm    
Andrew, this is good enough (my 5). I think this is one of the best methods. I would expect further discussions with OP.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900