I want to make a simple GUI API. Essentially the way it will work is the gui widget is basically a thread in an infinite loop. The thread has a pointer to the widget's class. The way I want it to work is basically similar to WinAPI. I would do something like this:
textbox->SendMessage("Click",args);
which is then added to its queue for processing. Eventually this will call a pointed function which would be the click event handler. Another thing I want to be able to do is safely 开发者_开发技巧get and set stuff in the class, without having to worry if the worker thread is using it. For example, if I send a message (which adds to a queue) while the worker is dequeing this might cause trouble. I'm using boost::thread. What exactly should I do for my situation?
Thanks
Is there a reason you're going down this path for GUI development?
There's a very good reason nearly all GUI libraries rely on a single thread for managing 'widgets'. Multithreading is hard; when writing controls with a large exposed interface you're going to need to be exceedingly careful in how you design it. As the number of threads (widgets) grows you'll also face scalability problems when you get near the operating system's thread limits, or failing that, you increase the load on the scheduler such that some threads begin to starve.
My advice would be to redesign with a typical single-threaded message pump that pushes input events into widgets and pulls out their resultant state.
This sounds a lot like the "Active Object" pattern, where an object runs calls to its methods in its own private thread.
Since you're using C++, you may find Herb Sutter's Effective Concurrency article on active objects useful.
精彩评论