Click here to Skip to main content
11,926,933 members (47,980 online)
Rate this:
Please Sign up or sign in to vote.
See more: VC8.0 C++

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

Posted 20-Jan-11 17:59pm
SAKryukov 20-Jan-11 23:04pm
No difference between static and non-static -- at all, and no problems. Both ways need synchronization.

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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.

This example uses Win32 Threads, but the principal is the same for all thread implementations like pthreads. They all take a user defined parameter.
SAKryukov 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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.151126.1 | Last Updated 20 Jan 2011
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100