From d5de65fdb1802cdf498d65d93397f290813c377c Mon Sep 17 00:00:00 2001 From: muqiuhan Date: Tue, 9 Sep 2025 06:17:00 +0000 Subject: deploy: 9665097f0fa0dae9f92123fac54d26c0818758a5 --- 2023/08/15/poll-error-attribute-in-OCaml/index.html | 1 - 1 file changed, 1 deletion(-) (limited to '2023/08/15/poll-error-attribute-in-OCaml/index.html') diff --git a/2023/08/15/poll-error-attribute-in-OCaml/index.html b/2023/08/15/poll-error-attribute-in-OCaml/index.html index a31bde90..d48bc2eb 100644 --- a/2023/08/15/poll-error-attribute-in-OCaml/index.html +++ b/2023/08/15/poll-error-attribute-in-OCaml/index.html @@ -197,7 +197,6 @@

OCaml 编译器提供了一个名为 [@poll error] 的annotation,可以在函数中使用它来确保该函数不包含safe point。

所以通过使用 [@poll error] 就可以创建在Domain内原子性执行的函数,也就是说,基于此特性可以实现单个Domain内线程安全的数据结构,例如 thread-table 便是使用这个特性实现的 Hash Table。可以看看它的 add 函数的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let[@poll error] add_atomically t buckets n i before after =
t.rehash = 0 && buckets == t.buckets
&& before == Array.unsafe_get buckets i
&& begin
Array.unsafe_set buckets i after;
let length = t.length + 1 in
t.length <- length;
if n < length && n < max_buckets_div_2 then t.rehash <- n * 2;
true
end

let rec add t k' v' =
let h = Mix.int k' in
maybe_rehash t;
let buckets = t.buckets in
let n = Array.length buckets in
let i = h land (n - 1) in
let before = Array.unsafe_get buckets i in
let after = Cons (k', v', before) in
if not (add_atomically t buckets n i before after) then add t k' v'
-

相比使用 Stdlib.Mutex,这种无锁实现会有更好的性能(特别是对于只读操作),并且还允许例如信号处理之类的上下文操作。

-- cgit v1.2.3