You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Native extensions are by default considered thread-unsafe for maximum compatibility with CRuby and use the global extension lock (unless `--cexts-lock=false` is used).
10
10
11
-
Extensions can mark themselves as thread-safe either by using `rb_ext_ractor_safe()` or `rb_ext_thread_safe()` (TruffleRuby-specific).
11
+
Extensions can mark themselves as thread-safe either by using `rb_ext_ractor_safe()` or `rb_ext_thread_safe()` (the latter is TruffleRuby-specific).
12
12
Such extensions are then run by TruffleRuby without a global extension lock, i.e. in parallel.
13
13
14
14
Here is an example of an extension marking itself as Ractor-safe.
@@ -34,6 +34,27 @@ void Init_my_extension(void) {
34
34
}
35
35
```
36
36
37
+
It is possible to mark individual methods as Ractor/Thread-safe by using `rb_ext_ractor_safe/rb_ext_thread_safe(true/false)` around them (these functions actually set a Fiber-local flag):
38
+
```c
39
+
voidInit_my_extension(void) {
40
+
#ifdef HAVE_RB_EXT_RACTOR_SAFE
41
+
rb_ext_ractor_safe(true);
42
+
#endif
43
+
rb_define_method(myClass, "ractor_safe_method", foo_impl, 0); // The C function foo_impl can be called from multiple threads in parallel
44
+
// more Ractor-safe methods
45
+
46
+
#ifdef HAVE_RB_EXT_RACTOR_SAFE
47
+
rb_ext_ractor_safe(false);
48
+
#endif
49
+
rb_define_method(myClass, "ractor_unsafe_method", bar_impl, 0); // The C function bar_impl needs a global extension lock for correctness
50
+
// more Ractor-unsafe methods
51
+
}
52
+
```
53
+
54
+
Other Ruby C API functions taking a C function like `rb_proc_new()` do not use the global extension lock if:
55
+
* Called inside the `Init_my_extension` and `rb_ext_ractor_safe(true)` / `rb_ext_thread_safe(true)` are used.
56
+
* Called outside the `Init_my_extension` and the calling function does not hold the global extension lock.
57
+
37
58
The conditions for an extension to be thread-safe are the following.
38
59
This is similar to [the conditions for Ractor-safe extensions](https://github.com/ruby/ruby/blob/master/doc/extension.rdoc#appendix-f-ractor-support-) but not all conditions are necessary.
39
60
1. The extension should make it clear in its documentation which objects are safe to share between threads and which are not.
0 commit comments