thread safe callback function
How can i make a callback function thread safe. This function will be called by different threads to update UI. This callback function will have an HWND parameter which will be filled by the caller. The function will use this HWND parameter to update GUI. HWND will be different for different calls.
Please tell me how can i make this callback thread safe.
Regard开发者_运维技巧s.
John
Please tell me how can i make this callback thread safe.
If there's no state required by the callback function, it's already threadsafe, unless the GUI functions themselves are not threadsafe (see the 2nd half of this answer).
If there is state required, include a mutex in that state, and lock the mutex during any read/write accesses.
There are more complex lock paradigms (e.g. multiple-reader/single-writer locks) but you probably won't need that for a GUI.
The other issue for GUIs (true for Java Swing; I can't remember whether this is true for win32 or not) is that GUI operations should usually be performed in one particular thread. In win32, that's the reason for posting and sending messages (which are processed by one thread).
If you wanted to use this approach, anytime you want to perform a GUI operation, you should check whether you are in the GUI thread (can't remember how to do that in win32), or perform a PostMessage() call to kick off particular GUI operations.
精彩评论