|
-
November 19th, 2008, 12:24 PM
#3
Re: How to use CCriticalSection
 Originally Posted by VictorN
Is your worker thread only writes data into array and your main GUI thread only reads this data in, then a better way would be not use any synchronization at all.
Just define some user message (from the WM_APP range), let the worker thread PostMessage this message and pass the data as PostMessage parameter(s), and let the main thread handle this message, fill data in the array and work with this array.
Just to be clearer, these two paragraphs describe two different architectures. In the first, synchronization is indeed needed if a worker is writing data into an array and the GUI thread is reading it from the same array. The reason synchronization is needed is precisely because access to the same memory is being made by two different threads. Consider a case where the worker is deleting data from the array. Without synchronization, the GUI thread could easily go past the new end of the array, into corrupted memory.
When Victor says (at the end of the first paragraph) that "a better way would be not use any synchronization at all", he is intorducing a different architecture, which is described in the second paragraph. In this second architecture, the worker thread does not touch the array. The worker thread's sole job is to supply the GUI thread with data for the array, leaving the GUI thread with the responsibility of actually storing the data into the array. This second architecture does not need synchronization for the reason that there is no shared memory, i.e., only the GUI thread ever touches the array.
In answer to some others of your question, it probably crashes when synchronization is not used for precisely the reasons described above. The array is a templated collection class. When the worker adds data to the array, if there is not sufficient memory already allocated for the array, a typical collection class will re-allocate memory for the array and copy contents to the new allocation. Meanwhile, the GUI thread is still operating on the older values, which are now all meaningless and corrupted memory locations. You thus need synchronization.
When you add synchronization, you need to tell the GUI thread when to display. Add some sort of signalling. The worker could, for example, PostMessage a custom message to the GUI thread when it is done adding data to the array. The handler in the GUI thread for this custom message could then call "Invalidate()" or some such, so as to cause the GUI thread to re-paint the sceen with the newly added data.
Mike
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|