Click here to Skip to main content
11,710,423 members (80,866 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: VC8.0

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

Posted 20-Jan-11 16:59pm
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
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 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 Sergey Alexandrovich Kryukov 549
1 OriginalGriff 255
2 Peter Leow 174
3 Abhinav S 110
4 Suvendu Shekhar Giri 90
0 Abhinav S 60
1 Member 4653839 40
2 barneyman 35
3 Sergey Alexandrovich Kryukov 35
4 Member 11793820 35

Advertise | Privacy | Mobile
Web01 | 2.8.150819.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