【翻譯四】什麼是重排序

What is meant by reordering?

There are a number of cases in which accesses to program variables (object instance fields, class static fields, and array elements) may appear to execute in a different order than was specified by the program. The compiler is free to take liberties with the ordering of instructions in the name of optimization. Processors may execute instructions out of order under certain circumstances. Data may be moved between registers, processor caches, and main memory in different order than specified by the program.數組

在程序中,每每有一些狀況,程序執行時對變量(實例字段、類靜態字段、數組元素)的訪問順序與代碼指定的不一樣。編譯器以優化的名義,能夠隨意對指令排序。在某種狀況下,處理器也能夠不按順序執行指令。數據也可能以不一樣的順序在寄存器、處理器緩存、主內存間轉移。緩存

For example, if a thread writes to field a and then to field b, and the value of b does not depend on the value of a, then the compiler is free to reorder these operations, and the cache is free to flush b to main memory before a. There are a number of potential sources of reordering, such as the compiler, the JIT, and the cache.多線程

例如,若是一個線程先給a賦值,再給b賦值,給b賦值時不依賴於a是否被賦值,那麼編譯器就能夠自由的對這兩步操做重排序,緩存也能夠自由地重排序,先將b刷進主內存,再將a刷進主內存。有許多引起重排序的緣由,如編譯器,JIT(Just-In-Time 準時制),處理器緩存。app

The compiler, runtime, and hardware are supposed to conspire to create the illusion of as-if-serial semantics, which means that in a single-threaded program, the program should not be able to observe the effects of reorderings. However, reorderings can come into play in incorrectly synchronized multithreaded programs, where one thread is able to observe the effects of other threads, and may be able to detect that variable accesses become visible to other threads in a different order than executed or specified in the program.優化

編譯器、運行時和硬件應該協同創造一個as-if-serial的語義,這個語義意味着在單線程程序中,程序不該發生重排序。然而,重排序會在未正確同步的多線程程序中發生,若是一條線程能觀察到其餘線程時,就有可能看到可見的變量,而這個順序是與程序所執行或所指定的不相同的。線程

Most of the time, one thread doesn't care what the other is doing. But when it does, that's what synchronization is for.排序

大多數時間裏,一條線程不須要關心其餘線程在作什麼。但當它要關心的時候,就是要同步的時候了。內存

相關文章
相關標籤/搜索