Accessing dialog box item from multiple threads (C++)
I h开发者_开发知识库ave a dialog box with some check box control items.
This dialog box can create a worker thread, which is able to access some of these control items while it is running.
But user can also modify these check box control items while the worker thread is running.
Although it is unlikely, it can happen that the thread tries to read some of these items at the exact moment when the user want to change them.
How can I protect the dialog box item from concurrent access between the main thread and the worker thread?
I suppose I should create a mutex, and it is easy to use this mutex from the worker thread, but I don't see where I could insert code for locking the dialog item with the same mutex when the user want to change it.
Is there somebody who could help me with that?
Thanks in advance.
GingkoYou haven't stated which platform you are using, so I'm going to assume that whatever platform it is, it follows the common rules that only the UI thread can access UI controls. With that rule in place you have the obvious corollary that the other threads can't read the check box state directly.
The solution is as follows:
- Create some private boolean fields corresponding to the check boxes in the object representing the dialog.
- Whenever the user modifies a check-box, update the corresponding boolean field.
- Expose those fields as read-only properties for the other threads to read.
- (optional) Protect all access to the boolean fields with a mutex.
Item 4 is optional because on all architectures I know there is no danger of tearing when accessing a boolean field.
The whole point of this is to avoid the problem that reading and writing UI control state is not thread-safe. But in the overall design you outline you are never going to be free of a data race. When your worker thread reads the state the user may just have changed it, or may be just about to change it. You can't know and once you allow the worker thread to operate in parallel with the UI thread you must embrace that fact.
精彩评论