Debian Codegraph @

include/ruby/internal/intern/thread.h

raw
1 #ifndef RBIMPL_INTERN_THREAD_H /*-*-C++-*-vi:se ft=cpp:*/
2 #define RBIMPL_INTERN_THREAD_H
3 /**
4 * @file
5 * @author Ruby developers <[email protected]>
6 * @copyright This file is a part of the programming language Ruby.
7 * Permission is hereby granted, to either redistribute and/or
8 * modify this file, provided that the conditions mentioned in the
9 * file COPYING are met. Consult the file for details.
10 * @warning Symbols prefixed with either `RBIMPL` or `rbimpl` are
11 * implementation details. Don't take them as canon. They could
12 * rapidly appear then vanish. The name (path) of this header file
13 * is also an implementation detail. Do not expect it to persist
14 * at the place it is now. Developers are free to move it anywhere
15 * anytime at will.
16 * @note To ruby-core: remember that this header can be possibly
17 * recursively included from extension libraries written in C++.
18 * Do not expect for instance `__VA_ARGS__` is always available.
19 * We assume C99 for ruby itself but we don't assume languages of
20 * extension libraries. They could be written in C++98.
21 * @brief Public APIs related to ::rb_cThread.
22 */
23 #include "ruby/internal/attr/nonnull.h"
24 #include "ruby/internal/cast.h"
25 #include "ruby/internal/config.h"
26 #include "ruby/internal/dllexport.h"
27 #include "ruby/internal/value.h"
28
29 RBIMPL_SYMBOL_EXPORT_BEGIN()
30
31 struct timeval;
32
33 /* thread.c */
34
35 /**
36 * Tries to switch to another thread. This function blocks until the current
37 * thread re-acquires the GVL.
38 *
39 * @exception rb_eInterrupt Operation interrupted.
40 */
41 void rb_thread_schedule(void);
42
43 /**
44 * Blocks the current thread until the given file descriptor is ready to be
45 * read.
46 *
47 * @param[in] fd A file descriptor.
48 * @exception rb_eIOError Closed stream.
49 * @exception rb_eSystemCallError Situations like EBADF.
50 */
51 int rb_thread_wait_fd(int fd);
52
53 /**
54 * Identical to rb_thread_wait_fd(), except it blocks the current thread until
55 * the given file descriptor is ready to be written.
56 *
57 * @param[in] fd A file descriptor.
58 * @exception rb_eIOError Closed stream.
59 * @exception rb_eSystemCallError Situations like EBADF.
60 */
61 int rb_thread_fd_writable(int fd);
62
63 /**
64 * Notifies a closing of a file descriptor to other threads. Multiple threads
65 * can wait for the given file descriptor at once. If such file descriptor is
66 * closed, threads need to start propagating their exceptions. This is the API
67 * to kick that process.
68 *
69 * @param[in] fd A file descriptor.
70 * @note This function blocks until all the threads waiting for such fd
71 * have woken up.
72 */
73 void rb_thread_fd_close(int fd);
74
75 /**
76 * Checks if the thread this function is running is the only thread that is
77 * currently alive.
78 *
79 * @retval 1 Yes it is.
80 * @retval 0 No it isn't.
81 *
82 * @internal
83 *
84 * Above description is in fact inaccurate. There are Ractors these days.
85 */
86 int rb_thread_alone(void);
87
88 /**
89 * Blocks for the given period of time.
90 *
91 * @warning This function can be interrupted by signals.
92 * @param[in] sec Duration in seconds.
93 * @exception rb_eInterrupt Interrupted.
94 */
95 void rb_thread_sleep(int sec);
96
97 /**
98 * Blocks indefinitely.
99 *
100 * @exception rb_eInterrupt Interrupted.
101 */
102 void rb_thread_sleep_forever(void);
103
104 /**
105 * Identical to rb_thread_sleep_forever(), except the thread calling this
106 * function is considered "dead" when our deadlock checker is triggered.
107 *
108 * @exception rb_eInterrupt Interrupted.
109 */
110 void rb_thread_sleep_deadly(void);
111
112 /**
113 * Stops the current thread. This is not the end of the thread's lifecycle. A
114 * stopped thread can later be woken up.
115 *
116 * @exception rb_eThreadError Stopping this thread would deadlock.
117 * @retval ::RUBY_Qnil Always.
118 *
119 * @internal
120 *
121 * The return value makes no sense at all.
122 */
123 VALUE rb_thread_stop(void);
124
125 /**
126 * Marks a given thread as eligible for scheduling.
127 *
128 * @note It may still remain blocked on I/O.
129 * @note This does not invoke the scheduler itself.
130 *
131 * @param[out] thread Thread in question to wake up.
132 * @exception rb_eThreadError Stop flogging a dead horse.
133 * @return The passed thread.
134 * @post The passed thread is made runnable.
135 */
136 VALUE rb_thread_wakeup(VALUE thread);
137
138 /**
139 * Identical to rb_thread_wakeup(), except it doesn't raise on an already
140 * killed thread.
141 *
142 * @param[out] thread A thread to wake up.
143 * @retval RUBY_Qnil `thread` is already killed.
144 * @retval otherwise `thread` is alive.
145 * @post The passed thread is made runnable, unless killed.
146 */
147 VALUE rb_thread_wakeup_alive(VALUE thread);
148
149 /**
150 * This is a rb_thread_wakeup() + rb_thread_schedule() combo.
151 *
152 * @note There is no guarantee that this function yields to the passed
153 * thread. It may still remain blocked on I/O.
154 * @param[out] thread Thread in question to wake up.
155 * @exception rb_eThreadError Stop flogging a dead horse.
156 * @return The passed thread.
157 */
158 VALUE rb_thread_run(VALUE thread);
159
160 /**
161 * Terminates the given thread. Unlike a stopped thread, a killed thread could
162 * never be revived. This function does return, when passed e.g. an already
163 * killed thread. But if the passed thread is the only one, or a special
164 * thread called "main", then it also terminates the entire process.
165 *
166 * @param[out] thread The thread to terminate.
167 * @exception rb_eFatal The passed thread is the running thread.
168 * @exception rb_eSystemExit The passed thread is the last thread.
169 * @return The passed thread.
170 * @post Either the passed thread, or the process entirely, is killed.
171 *
172 * @internal
173 *
174 * It seems killing the main thread also kills the entire process even if there
175 * are multiple running ractors. No idea why.
176 */
177 VALUE rb_thread_kill(VALUE thread);
178
179 RBIMPL_ATTR_NONNULL((1))
180 /**
181 * Creates a Ruby thread that is backended by a C function.
182 *
183 * @param[in] f The function to run on a thread.
184 * @param[in,out] g Passed through to `f`.
185 * @exception rb_eThreadError Could not create a ruby thread.
186 * @exception rb_eSystemCallError Situations like `EPERM`.
187 * @return Allocated instance of ::rb_cThread.
188 * @note This doesn't wait for anything.
189 */
190 VALUE rb_thread_create(VALUE (*f)(void *g), void *g);
191
192 /**
193 * Identical to rb_thread_sleep(), except it takes struct `timeval` instead.
194 *
195 * @warning This function can be interrupted by signals.
196 * @param[in] time Duration.
197 * @exception rb_eInterrupt Interrupted.
198 */
199 void rb_thread_wait_for(struct timeval time);
200
201 /**
202 * Obtains the "current" thread.
203 *
204 * @return The current thread of the current ractor of the current execution
205 * context.
206 * @pre This function must be called from a thread controlled by ruby.
207 */
208 VALUE rb_thread_current(void);
209
210 /**
211 * Obtains the "main" thread. There are threads called main. Historically the
212 * (only) main thread was the one which runs when the process boots. Now that
213 * we have Ractor, there are more than one main threads.
214 *
215 * @return The main thread of the current ractor of the current execution
216 * context.
217 * @pre This function must be called from a thread controlled by ruby.
218 */
219 VALUE rb_thread_main(void);
220
221 /**
222 * This badly named function reads from a Fiber local storage. When this
223 * function was born there was no such thing like a Fiber. The world was
224 * innocent. But now... This is a Fiber local storage. Sorry.
225 *
226 * @param[in] thread Thread that the target Fiber is running.
227 * @param[in] key The name of the Fiber local storage to read.
228 * @retval RUBY_Qnil No such storage.
229 * @retval otherwise The value stored at `key`.
230 * @note There in fact are "true" thread local storage, but Ruby doesn't
231 * provide any interface of them to you, C programmers.
232 */
233 VALUE rb_thread_local_aref(VALUE thread, ID key);
234
235 /**
236 * This badly named function writes to a Fiber local storage. When this
237 * function was born there was no such thing like a Fiber. The world was
238 * innocent. But now... This is a Fiber local storage. Sorry.
239 *
240 * @param[in] thread Thread that the target Fiber is running.
241 * @param[in] key The name of the Fiber local storage to write.
242 * @param[in] val The new value of the storage.
243 * @exception rb_eFrozenError `thread` is frozen.
244 * @return The passed `val` as-is.
245 * @post Fiber local storage `key` has value of `val`.
246 * @note There in fact are "true" thread local storage, but Ruby doesn't
247 * provide any interface of them to you, C programmers.
248 */
249 VALUE rb_thread_local_aset(VALUE thread, ID key, VALUE val);
250
251 /**
252 * A `pthread_atfork(3posix)`-like API. Ruby expects its child processes to
253 * call this function at the very beginning of their processes. If you plan to
254 * fork a process don't forget to call it.
255 */
256 void rb_thread_atfork(void);
257
258 /**
259 * :FIXME: situation of this function is unclear. It seems nobody uses it.
260 * Maybe a good idea to KonMari.
261 */
262 void rb_thread_atfork_before_exec(void);
263
264 /**
265 * "Recursion" API entry point. This basically calls the given function with
266 * the given arguments, but additionally with recursion flag. The flag is set
267 * to 1 if the execution have already experienced the passed `g` parameter
268 * before.
269 *
270 * @param[in] f The function that possibly recurs.
271 * @param[in,out] g Passed as-is to `f`.
272 * @param[in,out] h Passed as-is to `f`.
273 * @return The return value of f.
274 */
275 VALUE rb_exec_recursive(VALUE (*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h);
276
277 /**
278 * Identical to rb_exec_recursive(), except it checks for the recursion on the
279 * ordered pair of `{ g, p }` instead of just `g`.
280 *
281 * @param[in] f The function that possibly recurs.
282 * @param[in,out] g Passed as-is to `f`.
283 * @param[in] p Paired object for recursion detection.
284 * @param[in,out] h Passed as-is to `f`.
285 */
286 VALUE rb_exec_recursive_paired(VALUE (*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h);
287
288 /**
289 * Identical to rb_exec_recursive(), except it calls `f` for outermost
290 * recursion only. Inner recursions yield calls to rb_throw_obj().
291 *
292 * @param[in] f The function that possibly recurs.
293 * @param[in,out] g Passed as-is to `f`.
294 * @param[in,out] h Passed as-is to `f`.
295 * @return The return value of f.
296 *
297 * @internal
298 *
299 * It seems nobody uses the "it calls rb_throw_obj()" part of this function.
300 * @shyouhei doesn't understand the needs.
301 */
302 VALUE rb_exec_recursive_outer(VALUE (*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h);
303
304 /**
305 * Identical to rb_exec_recursive_outer(), except it checks for the recursion
306 * on the ordered pair of `{ g, p }` instead of just `g`. It can also be seen
307 * as a routine identical to rb_exec_recursive_paired(), except it calls `f`
308 * for outermost recursion only. Inner recursions yield calls to
309 * rb_throw_obj().
310 *
311 * @param[in] f The function that possibly recurs.
312 * @param[in,out] g Passed as-is to `f`.
313 * @param[in] p Paired object for recursion detection.
314 * @param[in,out] h Passed as-is to `f`.
315 *
316 * @internal
317 *
318 * It seems nobody uses the "it calls rb_throw_obj()" part of this function.
319 * @shyouhei doesn't understand the needs.
320 */
321 VALUE rb_exec_recursive_paired_outer(VALUE (*f)(VALUE g, VALUE h, int r), VALUE g, VALUE p, VALUE h);
322
323 /**
324 * This is the type of UBFs. An UBF is a function that unblocks a blocking
325 * region. For instance when a thread is blocking due to `pselect(3posix)`, it
326 * is highly expected that `pthread_kill(3posix)` can interrupt the system call
327 * and the thread could revive. Or when a thread is blocking due to
328 * `waitpid(3posix)`, it is highly expected that killing the waited process
329 * should suffice. An UBF is a function that does such things. Designing your
330 * own UBF needs deep understanding of why your blocking region blocks, how
331 * threads work in ruby, and a matter of luck. It often is the case you simply
332 * cannot cancel something that had already begun.
333 *
334 * @see rb_thread_call_without_gvl()
335 */
336 typedef void rb_unblock_function_t(void *);
337
338 /**
339 * @private
340 *
341 * This is an implementation detail. Must be a mistake to be here.
342 *
343 * @internal
344 *
345 * Why is this function type different from what rb_thread_call_without_gvl()
346 * takes?
347 */
348 typedef VALUE rb_blocking_function_t(void *);
349
350 /**
351 * Checks for interrupts. In ruby, signals are masked by default. You can
352 * call this function at will to check if there are pending signals. In case
353 * there are, they would be handled in this function.
354 *
355 * If your extension library has a function that takes a long time, consider
356 * calling it periodically.
357 *
358 * @note It might switch to another thread.
359 */
360 void rb_thread_check_ints(void);
361
362 /**
363 * Checks if the thread's execution was recently interrupted. If called from
364 * that thread, this function can be used to detect spurious wake-ups.
365 *
366 * @param[in] thval Thread in question.
367 * @retval 0 The thread was not interrupted.
368 * @retval otherwise The thread was interrupted recently.
369 *
370 * @internal
371 *
372 * Above description is not a lie. But actually the return value is an opaque
373 * trap vector. If you know which bit means which, you can know what happened.
374 */
375 int rb_thread_interrupted(VALUE thval);
376
377 /**
378 * A special UBF for blocking IO operations. You need deep understanding of
379 * what this actually do before using. Basically you should not use it from
380 * extension libraries. It is too easy to mess up.
381 */
382 #define RUBY_UBF_IO RBIMPL_CAST((rb_unblock_function_t *)-1)
383
384 /**
385 * A special UBF for blocking process operations. You need deep understanding
386 * of what this actually do before using. Basically you should not use it from
387 * extension libraries. It is too easy to mess up.
388 */
389 #define RUBY_UBF_PROCESS RBIMPL_CAST((rb_unblock_function_t *)-1)
390
391 /* thread_sync.c */
392
393 /**
394 * Creates a mutex.
395 *
396 * @return An allocated instance of rb_cMutex.
397 */
398 VALUE rb_mutex_new(void);
399
400 /**
401 * Queries if there are any threads that holds the lock.
402 *
403 * @param[in] mutex The mutex in question.
404 * @retval RUBY_Qtrue The mutex is locked by someone.
405 * @retval RUBY_Qfalse The mutex is not locked by anyone.
406 */
407 VALUE rb_mutex_locked_p(VALUE mutex);
408
409 /**
410 * Attempts to lock the mutex, without waiting for other threads to unlock it.
411 * Failure in locking the mutex can be detected by the return value.
412 *
413 * @param[out] mutex The mutex to lock.
414 * @retval RUBY_Qtrue Successfully locked by the current thread.
415 * @retval RUBY_Qfalse Otherwise.
416 * @note This function also returns ::RUBY_Qfalse when the mutex is
417 * already owned by the calling thread itself.
418 */
419 VALUE rb_mutex_trylock(VALUE mutex);
420
421 /**
422 * Attempts to lock the mutex. It waits until the mutex gets available.
423 *
424 * @param[out] mutex The mutex to lock.
425 * @exception rb_eThreadError Recursive deadlock situation.
426 * @return The passed mutex.
427 * @post The mutex is owned by the current thread.
428 */
429 VALUE rb_mutex_lock(VALUE mutex);
430
431 /**
432 * Releases the mutex.
433 *
434 * @param[out] mutex The mutex to unlock.
435 * @exception rb_eThreadError The mutex is not owned by the current thread.
436 * @return The passed mutex.
437 * @post Upon successful return the passed mutex is no longer owned by
438 * the current thread.
439 */
440 VALUE rb_mutex_unlock(VALUE mutex);
441
442 /**
443 * Releases the lock held in the mutex and waits for the period of time;
444 * reacquires the lock on wakeup.
445 *
446 * @pre The lock has to be owned by the current thread beforehand.
447 * @param[out] self The target mutex.
448 * @param[in] timeout Duration, in seconds, in ::rb_cNumeric.
449 * @exception rb_eArgError `timeout` is negative.
450 * @exception rb_eRangeError `timeout` is out of range of `time_t`.
451 * @exception rb_eThreadError The mutex is not owned by the current thread.
452 * @return Number of seconds it actually slept.
453 * @warning It is a failure not to check the return value. This function
454 * can return spuriously for various reasons. Maybe other threads
455 * can rb_thread_wakeup(). Maybe an end user can press the
456 * Control and C key from the interactive console. On the other
457 * hand it can also take longer than the specified. The mutex
458 * could be locked by someone else. It waits then.
459 * @post Upon successful return the passed mutex is owned by the current
460 * thread.
461 *
462 * @internal
463 *
464 * This function is called from `ConditionVariable#wait`. So it is not a
465 * deprecated feature. However @shyouhei have never seen any similar mutex
466 * primitive available in any other languages than Ruby.
467 *
468 * EDIT: In 2021, @shyouhei asked @ko1 in person about this API. He answered
469 * that it is his invention. The motivation behind its design is to eliminate
470 * needs of condition variables as primitives. Unlike other languages, Ruby's
471 * `ConditionVariable` class was written in pure-Ruby initially. We don't have
472 * to implement machine-native condition variables in assembly each time we
473 * port Ruby to a new architecture. This function made it possible. "I felt I
474 * was a genius when this idea came to me", said @ko1.
475 *
476 * `rb_cConditionVariable` is now written in C for speed, though.
477 */
478 VALUE rb_mutex_sleep(VALUE self, VALUE timeout);
479
480 /**
481 * Obtains the lock, runs the passed function, and releases the lock when it
482 * completes.
483 *
484 * @param[out] mutex The mutex to lock.
485 * @param[in] func What to do during the mutex is locked.
486 * @param[in,out] arg Passed as-is to `func`.
487 */
488 VALUE rb_mutex_synchronize(VALUE mutex, VALUE (*func)(VALUE arg), VALUE arg);
489
490 RBIMPL_SYMBOL_EXPORT_END()
491
492 #endif /* RBIMPL_INTERN_THREAD_H */