Have main thread wait for a boost thread complete a task (but not finish)
I have found plenty on making one thread wait for another to finish executing before continuing, but that is not what I wanted to do. I am not very familiar with using any multi-threading apis but right now I'm trying to learn boost. My situation is that I am using my main thread (the starting one from int main()) to create an instance of a class that is in charge of interacting with the main GUI. A class function is then called that creates a boost thread which in turn creates the GUI and runs the message pump. The thing I want to do is when my main thread calls the classes member function to create the GUI, I don't want that function to return until I tell it to from the newly created thread. This way my main thread can't continue and call more functions from the GUI class that interact with the GUI thread until that thread has completed GUI creation and entered the message loop. I think I may be able to figure it out if it was multiple boost thread objects interacting with each other, but when it is the main thread (non-boost object) interacting with a boost thread ob开发者_StackOverflow中文版ject, I get lost. Eventually I want a loop in my main thread to call a class function (among other tasks) to check if the user as entered any new input into the GUI (buy any changes detected by the message loop being updated into a struct and changing a bool to tell the main thread in the class function a change has occurred). Any suggestions for any of this would be greatly appreciated.
This is the member function called by the main thread.
int ANNGUI::CreateGUI() { GUIMain = new Main(); GUIThread = new boost::thread(boost::bind(&Main::MainThreadFunc, GUIMain)); return 0; };
This is the boost thread starting function.
void Main::MainThreadFunc() { ANNVariables = new GUIVariables; WndProc = new WindowProcedure; ANNWindowsClass = new WindowsClass(ANNVariables, WndProc); ANNWindow = new MainWindow(ANNVariables); GUIMessagePump = new MessagePump; ANNWindow->ShowWindows(); while(true) { GUIMessagePump->ProcessMessage(); } };
BTW, everything compiles fine and when I run it, it works I just put a sleep() in the main thread so I can play with the GUI a little.
If you want to wait for the thread to finish simply use join() (http://www.boost.org/doc/libs/1_45_0/doc/html/thread/thread_management.html#thread.thread_management.thread.join)
If you are waiting for a signal a simple solution is to use a mutex. The barrier mutex of boost should work for you:
http://www.boost.org/doc/libs/1_45_0/doc/html/thread/synchronization.html#thread.synchronization.barriers
You can boost mutex from boost threads or non boost threads.
You would use a condition variable for this.
精彩评论