锁定与互锁 [英] lock vs Interlocked.Exchange

查看:92
本文介绍了锁定与互锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,该应用程序不断(+ -100ms)从PLC读取订单,然后将它们放入一个模型中,然后由多个客户端读取. 为此,我使用了lock语句.

I have an application which constantly (+-100ms) reads orders from a PLC and then puts them in a model which then gets read by multiple clients. For this im using the lock statement.

订单阅读线程:

lock (model) {
//update object
}

客户阅读:

lock (model) {
//serialize object to json string
}
send over tcp stream to client.

但是我也可以使用该更新:

But i could also use for the update :

Interlocked.ExChange(oldObj, newObj)

我不希望我的客户必须等待订单读取线程中发生的锁定. 而且我绝对不希望客户阻止我的订单读取线程.

I don't want my clients to have to wait for a lock that is happening in the Order Reading thread. And i definitly dont want client to block my Order Reading thread.

我最好使用Interlocked吗?

Am i better off using the Interlocked ?

感谢您的建议!

推荐答案

是的,您最好使用Interlocked,因为它效率更高,因为它通常被转换为单个原子操作.

Yes, you are better off using Interlocked as it's more efficient since it's mostly translated into a single atomic operation.

但是,如果您不介意客户端仍在阅读旧对象,甚至可以在没有互锁的情况下进行操作,而只需设置一个新实例.

However, if you don't mind the clients still reading the old object for a bit you can even do without the Interlocked and just set a new instance.

碰巧获得新实例的客户端将获得更新的数据,而没有碰到的客户端将在接下来的检查之一中获取它.

The client that happen to get the new instance will get the updated data and those that don't will get it in one of the next checks.

这篇关于锁定与互锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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