信号量会阻止指令重新排序吗? [英] Do semaphores prevent instruction reordering?

查看:86
本文介绍了信号量会阻止指令重新排序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找C#中可以等待的等效锁语句.有人建议通过以下方式使用二进制SemaphoreSlim:

I was looking for an awaitable equivalent of lock statements in C#. Some people suggest using a binary SemaphoreSlim in the following way:

await semaphore.WaitAsync().ConfigureAwait(false);
try
{
    //inner instructions
}
finally
{
    semaphore.Release();
}

我知道它存在一些问题(例如,它不是可重入的),但是我最大的担心是指令的重新排序.

I know it has some issues (e.g. it's not reentrant), but my biggest concern is with the instruction reeordering.

在普通的旧锁语句中,我们保证不会将锁的内部指令移出锁语句之前(或之后).这种信号量解决方案是否也一样?据我所见,文档没有提到此问题.

In plain old lock statements we have a guarantee that no inner instruction from the lock will be moved outside (before or after) the lock statement. Does the same hold for this semaphore solution? As far as I can see, the documentation doesn't mention this problem.

推荐答案

SemaphoreSlim和几乎所有其他同步构造都是使用Monitor(或其他基于Monitor)内部,这正是lock的实现方式,为您提供相同的保证.

SemaphoreSlim, and pretty much all of the other synchronization constructs, are built using a Monitor (or other types that are built on top of a Monitor) internally, which is exactly how a lock is implemented, giving you the same guarantees.

这篇关于信号量会阻止指令重新排序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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