多线程中的关键部分 [英] Critical Section in multithreading

查看:97
本文介绍了多线程中的关键部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在读取器/写入器多线程程序中,当只有两个线程(用于更新GUI的主线程和用于生成用于更新的数据的工作线程)时,读取器(主线程)是否需要锁定共享内存?还是读者(主线程)和作家(工人线程)都需要锁定?


谢谢,

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,

推荐答案

>>在阅读器过程中,我有一个while循环
>>检查data [i]是否可用,如果一段时间没有睡眠,
>>否则继续显示数据.有更好的检查方法吗?

使用 Control.Invoke [
>> 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


除了Espen建议的内容:它可以是System.Threading.DispatcherInvokeBeginInvoke方法(可以与WPF和Forms一起使用)或System.Windows.Forms.Control(仅表单,与控件的哪个实例无关,它只需要参与当前正在运行的System.Windows.Forms.Application).

有关其工作原理和用法示例的详细说明,请参阅我过去的回答:
Control.Invoke()与Control.BeginInvoke() [ ^ ],
Treeview Scanner和MD5的问题 [
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


两个线程.
锁的想法是,当您尝试获取锁时,要么获得它,要么被暂停等待它.如果只有一个线程锁定数据,那么它对任何事情都无济于事!
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!


这篇关于多线程中的关键部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆