Click here to Skip to main content
15,896,915 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In a reader/writer multithreaded program, when only two threads, main thread to update GUI and worker thread to generate data for updating, does a reader (main thread) need to lock a shared memory? or both reader (main thread) and writer (worker thread) need to lock?


Thanks,
Posted

>> In a reader procedure, I have a while loop
>> checking if data[i] is available, if not sleep for a certain time,
>> otherwise go ahead and display the data. Is there any better way to do the checking?

Use Control.Invoke[^] to notify the UI thread. The method passed to Invoke will be executed on the UI thread.

You can even pass the new data as a parameter, enabling you to drop the locking entirely ...

Regards
Espen Harlinn
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 9-May-11 20:43pm    
Good locking is no locking, good point. My 5.
--SA
Espen Harlinn 10-May-11 2:53am    
Thank you, SAKryukov!
Sergey Alexandrovich Kryukov 9-May-11 20:49pm    
I added my some details and explanation in my answer, please see.
--SA
In addition to what Espen suggested: it can be either method Invoke or BeginInvoke of System.Threading.Dispatcher (can work with both WPF and Forms) or System.Windows.Forms.Control (Forms only, does not matter what instance of control; it just has to participate in currently running System.Windows.Forms.Application).

For detailed explanation on how it works and usage samples, please see my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

—SA
 
Share this answer
 
Comments
Espen Harlinn 10-May-11 2:54am    
Good points, my 5
Sergey Alexandrovich Kryukov 10-May-11 12:41pm    
Thank you, Espen,
--SA
Both threads.
The idea of a lock is that when you try to acquire the lock, either you will get it or be suspended waiting for it. If only one thread locks the data, it does nothing useful to anything!
 
Share this answer
 
In a reader procedure, I have a while loop checking if data[i] is available, if not sleep for a certain time, otherwise go ahead and display the data. Is there any better way to do the checking?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900