跳轉到內容

Ada 程式設計/編譯指示/原子:3

來自華夏公益教科書,自由的教科書

幾乎總是錯誤地使用 原子易變 變數來進行 任務[1] 當一個物件是原子性的,它僅僅意味著它將被原子性地讀入或寫入記憶體。編譯器不會在訪問該物件時生成原子指令或記憶體屏障,它只會

  • 檢查架構是否保證原子記憶體載入和儲存,
  • 不允許一些編譯器最佳化,比如重新排序或抑制對物件的冗餘訪問。

例如,下面的程式碼,其中A是一個原子物件,可能會被誤解

A := A + 1;  -- Not an atomic increment!

編譯器不會(並且根據標準也不允許)生成原子增量指令來直接增量並從記憶體中更新變數A[2] 這是編譯器生成的程式碼

  A := A + 1;
804969f:	a1 04 95 05 08       	mov    0x8059504,%eax
80496a4:	40                   	inc    %eax
80496a5:	a3 04 95 05 08       	mov    %eax,0x8059504

如您所見,不會生成任何原子增量指令或測試並設定操作碼。與其他程式語言一樣,如果程式中需要這些特定指令,則必須使用機器程式碼插入顯式地編寫它們。[3]

上面的程式碼片段等效於以下程式碼(兩個程式碼序列生成完全相同的目的碼),其中T是一個(非原子)臨時變數

T := A;      -- A is copied atomically to local variable T
T := T + 1;  -- local variable T is incremented
A := T;      -- A is stored atomically

因此,從多個任務同時修改原子變數是不正確的。例如,兩個任務並行地增量一個計數器。即使在單處理器中,也應該使用其他 Ada 任務功能,例如受保護的物件。在多處理器中,根據記憶體一致性模型,使用各種原子或易變變數進行任務通訊會導致意想不到的後果。[2][4] 因此,在使用原子物件進行任務資料共享或同步時,尤其是在多處理器中,應格外小心。


參考文獻

[編輯 | 編輯原始碼]
  1. Arch Robison (2007-11-30). "Volatile: Almost Useless for Multi-Threaded Programming". Intel 軟體網路. Retrieved 2008-05-30. There is a widespread notion that the keyword volatile is good for multi-threaded programming (...) volatile is almost useless for multi-threaded programming.
  2. a b Ian Lance Taylor (2008-03-05). "Volatile". Retrieved 2008-05-28. Using [the C/C++ qualifier] volatile does not mean that the variable is accessed atomically; no locks are used. Using volatile does not mean that other cores in a multi-core system will see the memory accesses; no cache flushes are used. (...) Using volatile does not imply any sort of memory barrier; the processor can and will rearrange volatile memory accesses. (...) You should not use more than one such variable to communicate between any pair of threads, as there is no guarantee that the different threads will see the accesses in the same order.
  3. Laurent Guerby (1995). "C.5 Shared Variable Control". Ada 95 Rationale. Intermetrics. A need to access specific machine instructions arises sometimes (...). Examples include instructions that perform compound operations atomically on shared memory, such as test-and-set and compare-and-swap (...) {{cite book}}: |access-date= requires |url= (help); External link in |chapter= (help); Unknown parameter |month= ignored (help)
  4. Sarita V. Adve, Kourosh Gharachorloo (1996). "Shared Memory Consistency Models: A Tutorial" (PDF). IEEE Computer. 29 (12): 66–76. Retrieved 2008-05-28. {{cite journal}}: Unknown parameter |month= ignored (help)
華夏公益教科書