Bad practice with an MFC thread? How can I improve it?
I've had to alter some code I was handed. A live camera was constantly
filling a ring buffer with images, and on a given signal (which I've put in
as a button push for the moment) it stopped, leaving the last X images in
the buffer. The requirement came in such that it would run for X/2 more
frames after the button was pushed (i.e. when you push the button, the saved
video sequence is centred at the time of pushing the button).
Initially, I added a frame counter after the button was pushed, but found
that it caused the processor to spend all the time on counting and no more
time on updating the frames, so in essence it hung. Ideal time for threads,
I decided.
So now pushing the button calls an AfxBeginThread function, like this:
// Spawn thread to decide when to stop capturing
CWinThread* pStopCaptureThread;
pStopCaptureThread = AfxBeginThread (
fnStopCaptureThread,this,THREAD_PRIORITY_NORMAL,0,0,NULL);
Now, I understand that the fnStopCaptureThread function cannot be part of
the class within which this is all happening, so it's a global function.
However, I still need access to various class variables to do my
calculations, so that global function simply calls another function within
the original class object; the fnStopCaptureThread knows what object called
it because it is passed a 'this'.
Here's the body of that global function:
UINT fnStopCaptureThread(LPVOID lParam)
{
// Run the stopcapture code
Sequencer_class* dlg2 = (Sequencer_class*)lParam; // This kind of casting
is not the C++ way. Needs fixing. Moschops.
dlg2->StopCapture();
return 0;
}
StopCapture is the function, within the class, that handles counting frames
and working out when to stop. This all seems happy now, and it behaves as
expected thus far.
Looking at my code, I am aware that I've now got a thread playing with my
class object, and the code that spawned that thread is also still playing
with the exact same object, albeit never calling the StopCapture function.
I'm got this feeling that it's a bad idea to have in essence two threads
accessing the same object - presumably I won't be able to predict when
they'll do things relative to each other and could end up with problems.
This code section is quite simple and the variables StopCapture() is playing
with aren't touched by anything else until the thread is killed, but
nonetheless is seems like bad practice. My MFC experience is quite limited
(I'm usually an embedded coder) so I'm not sure if I'm seeing things, or if
this is a bad idea. Can anyone help me out? Is this bad practice, and if so,
what's a better way to do it?
'Chops