Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: VC8.0
Hi,
 
      How to make a thread procedure to access non-static member variables? Plaese give me a detial example..
 
Thanks,
Laje...
Posted 20-Jan-11 17:59pm
Comments
SAKryukov at 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
good
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.
}
 
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.
  Permalink  
v2
Comments
SAKryukov at 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
0 OriginalGriff 200
1 PIEBALDconsult 150
2 BillWoodruff 148
3 Jochen Arndt 135
4 DamithSL 130
0 OriginalGriff 5,695
1 DamithSL 4,506
2 Maciej Los 4,007
3 Kornfeld Eliyahu Peter 3,480
4 Sergey Alexandrovich Kryukov 3,190


Advertise | Privacy | Mobile
Web01 | 2.8.141216.1 | Last Updated 20 Jan 2011
Copyright © CodeProject, 1999-2014
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