gpt4 book ai didi

C#强制执行语句的顺序

转载 作者:搜寻专家 更新时间:2023-10-30 19:58:36 25 4
gpt4 key购买 nike

我的问题是关于 C# 中的执行顺序保证(通常也可能是 .Net)。我给出了一些我知道的 Java 示例来与之比较。

对于Java(来自“Java Concurrency in Practice”)

There is no guarantee that operations in one thread will be performed in the order given by the program, as long as the reordering is not detectable from within that thread-even if the reordering is apparent to other threads.

所以代码

  y = 10;
x = 5;
a = b + 10;

实际上可能在赋值 y = 10 之前赋值 a=b+10

和Java(来自同一本书)

Everything thread A does in or prior to a synchronized block is visible to thread B when it starts a synchronized block guarded by the same lock.

在 Java 中是这样

 y = 10;
synchronized(lockObject) {
x = 5;
}
a = b + 10;

y = 10 和 x = 5 都保证在 a = b + 10 之前运行(我不知道 y = 10 是否保证在 x = 5 之前运行)。

C#代码对C#语句的执行顺序做了什么保证

 y = 10;
lock(lockObject) {
x = 5;
}
a = b + 10;

我对可以提供明确引用或其他一些真正有意义的理由的答案特别感兴趣,因为这样的保证很难测试,因为它们是关于编译器被允许做什么,而不是它每次都做什么,因为当它们失败时,当线程以错误的顺序命中事物时,您将很难重现间歇性错误。

最佳答案

ISO 23270:2006 — Information technology—Programming languages—C# , §10.10 说(我引用):

10.10 Execution order Execution shall proceed such that the side effects of each executing thread are preserved at critical execution points. A side effect is defined as a read or write of a volatile field, a write to a non-volatile variable, a write to an external resource, and the throwing of an exception. The critical execution points at which the order of these side effects shall be preserved are references to volatile fields (§17.4.3), lock statements (§15.12), and thread creation and termination. An implementation is free to change the order of execution of a C# program, subject to the following constraints:

  • Data dependence is preserved within a thread of execution. That is, the value of each variable is computed as if all statements in the thread were executed in original program order. (emphasis mine).

  • Initialization ordering rules are preserved (§17.4.4, §17.4.5).

  • The ordering of side effects is preserved with respect to volatile reads and writes (§17.4.3). Additionally, an implementation need not evaluate part of an expression if it can deduce that that expression’s value is not used and that no needed side effects are produced (including any caused by calling a method or accessing a volatile field). When program execution is interrupted by an asynchronous event (such as an exception thrown by another thread), it is not guaranteed that the observable side effects are visible in the original program order.

其他 CLI 标准同样可以免费从 ISO 获得

但如果您担心多线程问题,则需要更深入地研究标准并了解有关原子性的规则。并非每个操作都保证是原子的。如果您是多线程的并且调用的方法引用局部变量(例如,实例或类(静态)成员)而不通过 lock、互斥锁、信号量或其他一些序列化技术序列化访问,你让自己对竞争条件持开放态度。

关于C#强制执行语句的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5996267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com