0

How do I pass data to another thread within the same process? I'm writing in c++ for windows 7 os. Consider the following thread for example:

DWORD WINAPI MyThreadFunction(LPVOID lpParam){
    while(true){
        //Do the thread's job here
        if(gotReturnInstruction()){
           //release memory etc.
           break;
        }
    }
    return 0;
}

This thread does its job as long as some other thread tells it to return. I have the handle to the thread, which I obtain from the 'CreateThread()' function. How do I pass the message to the thread (in this case the stop instruct)?

dandan78
  • 13,328
  • 13
  • 64
  • 78
The amateur programmer
  • 1,238
  • 3
  • 18
  • 38

1 Answers1

3

You don't "push" a stop instruction to a thread. Instead, that thread needs to "poll" for a stop instruction. If the thread is in a loop and performing work all the time, it could check for the stop instruction as simply as checking a global variable bool stopThread that is set by the main thread when it wants it to stop.

However, it will boost your CPU usage to 100% if the thread just sits in a while (true) loop doing nothing but checking this global variable. In this case, call WaitForSingleObject on an event which sleeps your thread until the main thread "signals the event" and wakes it up.

David Ching
  • 1,903
  • 17
  • 21