数组元素交换时的写入屏障

huangapple go评论66阅读模式
英文:

Write barrier when swapping array elements

问题

在由ocamlopt生成的AMD64汇编代码中,主路径中出现了以下行两次:

call	caml_modify@PLT

让我想知道...为什么在数组元素v_iv_j的存活性保持不变时会有两个写屏障?

(我简单地认为OCaml中的(非浮点数)数组是一些不可变长度的块,在标记阶段由GC遍历。)

或者:是否有一种特殊的OCaml习惯用法可以避免上述写屏障?

英文:

Consider the following code:

let swap_array_elements (arr:string array) (i:int) (j:int) =
  let v_i = arr.(i)
  and v_j = arr.(j) in
  arr.(i) <- v_j;
  arr.(j) <- v_i

In the AMD64 assembly code produced by ocamlopt the line below occurs twice in the main path:

call	caml_modify@PLT

Makes me wonder... why are there two write barriers when the liveness of the array elements v_i and v_j remains the same?

(I'm under the simplistic impression that (non-float) arrays in OCaml are blocks of some immutable length which are traversed by the GC in the marking phase.)

Or: is there a special OCaml idiom that allows me to avoid above write barriers?

答案1

得分: 4

以下是翻译好的内容:

由于您进行了两次独立的“写入”,据我所知,无法避免两次写入障碍。

特别是,由于交换不是原子性的,不能保证写入的值在“写入”时仍然在数组中。

此外,写入障碍还会跟踪写入主堆内的次堆(也称为幼儿堆)的指针,而交换可能会传播这些指针。

英文:

Since you are doing two separate writes, there are no way to avoid two write barrier as far as I know.

In particular, since the swap is not atomic, there is no guaranteed that the values written are still in the array at the time of of the writes.

There is moreover the issue that the write barrier also tracks pointers to the minor heap (aka the nursery heap) written inside the major heap, and the swap might spread those pointers.

huangapple
  • 本文由 发表于 2023年6月26日 17:36:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76555415.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定