getting a return from a thread...
-
Hi, first off thnx for the help guys getting a variable passed to a thread.. it works. but i need to get either a return and check the status of a variable in that thread at any given point of time. can you help me out..
-
Hi, first off thnx for the help guys getting a variable passed to a thread.. it works. but i need to get either a return and check the status of a variable in that thread at any given point of time. can you help me out..
The basic approach to this problem is to have a variable that is accessible to both the thread and your program, and then to use one of the thread synchronization primitives to 'protect' the variable from simultaneous access by the program and the thread. Here's a crude example, using an
int
as the shared data and a critical section for the thread sync primitive:static int SharedVariable = 0;
CCriticalSection SharedCS;static UINT Thread(LPVOID parameter);
int main()
{
AfxBeginThread(Thread,NULL);
for (;;) {
// get our shared variable
SharedCS.Lock();
int shared_variable = SharedVariable;
SharedCS.Unlock();
// do something with our copy
// ...
}
}
UINT Thread(LPVOID parameter)
{
// do stuff
SharedCS.Lock();
SharedVariable = 1;
SharedCS.Unlock();
// ...
// do more stuff
SharedCS.Lock();
SharedVariable = 2;
SharedCS.Unlock();
return 0;
}Each time either the main program or the thread function need to access the shared variable, they lock the critical section before the access, and unlock it afterward. When locked, a critical section guarantees that only one thread may 'enter' the section at a time. In my example, the main program is only reading the value, using it to monitor the progress of the thread.
Software Zen:
delete this;