aboutsummaryrefslogtreecommitdiffstats
path: root/thread.c
Commit message (Collapse)AuthorAgeFilesLines
* Thread specific storage APIsKoichi Sasada2023-12-081-0/+68
| | | | | | | | | | | | | | | | | | | | | This patch introduces thread specific storage APIs for tools which use `rb_internal_thread_event_hook` APIs. * `rb_internal_thread_specific_key_create()` to create a tool specific thread local storage key and allocate the storage if not available. * `rb_internal_thread_specific_set()` sets a data to thread and tool specific storage. * `rb_internal_thread_specific_get()` gets a data in thread and tool specific storage. Note that `rb_internal_thread_specific_get|set(thread_val, key)` can be called without GVL and safe for async signal and safe for multi-threading (native threads). So you can call it in any internal thread event hooks. Further more you can call it from other native threads. Of course `thread_val` should be living while accessing the data from this function. Note that you should not forget to clean up the set data.
* Refactor and fix the GVL instrumentation APIJean Boussier2023-11-271-4/+0
| | | | | | | | | | | | This entirely changes how it is tested. Rather than to use counters we now record the timeline of events with associated threads which makes it much easier to assert that certains events are only preceded by a specific event, and makes it much easier to debug unexpected timelines. Co-Authored-By: Étienne Barrié <etienne.barrie@gmail.com> Co-Authored-By: JP Camara <jp@jpcamara.com> Co-Authored-By: John Hawthorn <john@hawthorn.email>
* Embed ThreadGroup objectJean Boussier2023-11-221-8/+6
| | | | | These are rare but embedding them is trivial and make them fit in a 40B slot.
* GVL Instrumentation: pass thread->self as part of event dataJean Boussier2023-11-131-1/+1
| | | | | | | | | | | | | | | | | | | Context: https://github.com/ivoanjo/gvl-tracing/pull/4 Some hooks may want to collect data on a per thread basis. Right now the only way to identify the concerned thread is to use `rb_nativethread_self()` or similar, but even then because of the thread cache or MaNy, two distinct Ruby threads may report the same native thread id. By passing `thread->self`, hooks can use it as a key to store the metadata. NB: Most hooks are executed outside the GVL, so such data collection need to use a thread-safe data-structure, and shouldn't use the reference in other ways from inside the hook. They must also either pin that value or handle compaction.
* fix `native_thread_destroy()` timingKoichi Sasada2023-10-131-6/+3
| | | | | | | | With M:N thread scheduler, the native thread (NT) related resources should be freed when the NT is no longer needed. So the calling `native_thread_destroy()` at the end of `is will be freed when `thread_cleanup_func()` (at the end of Ruby thread) is not correct timing. Call it when the corresponding Ruby thread is collected.
* M:N thread scheduler for RactorsKoichi Sasada2023-10-121-169/+118
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | This patch introduce M:N thread scheduler for Ractor system. In general, M:N thread scheduler employs N native threads (OS threads) to manage M user-level threads (Ruby threads in this case). On the Ruby interpreter, 1 native thread is provided for 1 Ractor and all Ruby threads are managed by the native thread. From Ruby 1.9, the interpreter uses 1:1 thread scheduler which means 1 Ruby thread has 1 native thread. M:N scheduler change this strategy. Because of compatibility issue (and stableness issue of the implementation) main Ractor doesn't use M:N scheduler on default. On the other words, threads on the main Ractor will be managed with 1:1 thread scheduler. There are additional settings by environment variables: `RUBY_MN_THREADS=1` enables M:N thread scheduler on the main ractor. Note that non-main ractors use the M:N scheduler without this configuration. With this configuration, single ractor applications run threads on M:1 thread scheduler (green threads, user-level threads). `RUBY_MAX_CPU=n` specifies maximum number of native threads for M:N scheduler (default: 8). This patch will be reverted soon if non-easy issues are found. [Bug #19842]
* Optimize handle_interrupt(Exception => ..) as a common caseMatthew Draper2023-09-071-22/+55
| | | | | | | | | When interrupt behavior is configured for all possible exceptions using 'Exception', there's no need to iterate the pending exception's ancestors for hash lookups. More significantly, by storing the catch-all timing symbol directly in the mask stack, we can skip allocating the hash we would otherwise need.
* Skip allocation if handle_interrupt arg is already usableMatthew Draper2023-09-071-8/+17
| | | | | | If the supplied hash is already frozen and compare-by-identity, we can use it directly (still checking its contents are valid symbols), without making a new copy.
* Remove RARRAY_CONST_PTR_TRANSIENTPeter Zhu2023-07-131-1/+1
| | | | RARRAY_CONST_PTR now does the same things as RARRAY_CONST_PTR_TRANSIENT.
* Compile disabled code for thread cache alwaysNobuyoshi Nakada2023-06-301-0/+3
|
* Don't check for null pointer in calls to freePeter Zhu2023-06-301-1/+1
| | | | | | | | According to the C99 specification section 7.20.3.2 paragraph 2: > If ptr is a null pointer, no action occurs. So we do not need to check that the pointer is a null pointer.
* Fix `Thread#join(timeout)` when running inside the fiber scheduler. (#7903)Samuel Williams2023-06-031-0/+5
|
* Use a real Ruby mutex in rb_io_close_wait_list (#7884)KJ Tsanaktsidis2023-06-011-43/+53
| | | | | | | | | | | | | | | | | | | | | | Because a thread calling IO#close now blocks in a native condvar wait, it's possible for there to be _no_ threads left to actually handle incoming signals/ubf calls/etc. This manifested as failing tests on Solaris 10 (SPARC), because: * One thread called IO#close, which sent a SIGVTALRM to the other thread to interrupt it, and then waited on the condvar to be notified that the reading thread was done. * One thread was calling IO#read, but it hadn't yet reached the actual call to select(2) when the SIGVTALRM arrived, so it never unblocked itself. This results in a deadlock. The fix is to use a real Ruby mutex for the close lock; that way, the closing thread goes into sigwait-sleep and can keep trying to interrupt the select(2) thread. See the discussion in: https://github.com/ruby/ruby/pull/7865/
* * expand tabs. [ci skip]git2023-05-261-3/+3
| | | | Please consider using misc/expand_tabs.rb as a pre-commit hook.
* Fix busy-loop when waiting for file descriptors to closeKJ Tsanaktsidis2023-05-261-7/+43
| | | | | | | | | | | | | | | | | | | | | | | | | | When one thread is closing a file descriptor whilst another thread is concurrently reading it, we need to wait for the reading thread to be done with it to prevent a potential EBADF (or, worse, file descriptor reuse). At the moment, that is done by keeping a list of threads still using the file descriptor in io_close_fptr. It then continually calls rb_thread_schedule() in fptr_finalize_flush until said list is empty. That busy-looping seems to behave rather poorly on some OS's, particulary FreeBSD. It can cause the TestIO#test_race_gets_and_close test to fail (even with its very long 200 second timeout) because the closing thread starves out the using thread. To fix that, I introduce the concept of struct rb_io_close_wait_list; a list of threads still using a file descriptor that we want to close. We call `rb_notify_fd_close` to let the thread scheduler know we're closing a FD, which fills the list with threads. Then, we call rb_notify_fd_close_wait which will block the thread until all of the still-using threads are done. This is implemented with a condition variable sleep, so no busy-looping is required.
* Fix a potential busy-loop in the thread scheduler (esp. on FreeBSD)KJ Tsanaktsidis2023-05-261-1/+0
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | This patch fixes a potential busy-loop in the thread scheduler. If there are two threads, the main thread (where Ruby signal handlers must run) and a sleeping thread, it is possible for the following sequence of events to occur: * The sleeping thread is in native_sleep -> sigwait_sleep A signal * arives, kicking this thread out of rb_sigwait_sleep The sleeping * thread calls THREAD_BLOCKING_END and eventually thread_sched_to_running_common * the sleeping thread writes into the sigwait_fd pipe by calling rb_thread_wakeup_timer_thread * the sleeping thread re-loops around in native_sleep() because the desired sleep time has not actually yet expired * that calls rb_sigwait_sleep again the ppoll() in rb_sigwait_sleep * immediately returns because of the byte written into the sigwait_fd by rb_thread_wakeup_timer_thread * that wakes the thread up again and kicks the whole cycle off again. Such a loop can only be broken by the main thread waking up and handling the signal, such that ubf_threads_empty() below becomes true again; however this loop can actually keep things so busy (and cause so much contention on the main thread's interrupt_lock) that the main thread doesn't deal with the signal for many seconds. This seems particuarly likely on FreeBSD 13. (the cycle can also be broken by the sleeping thread finally elapsing its desired sleep time). The fix for _this_ loop is to only wakeup the timer thrad in thread_sched_to_running_common if the current thread is not itself the sigwait thread. An almost identical loop also happens in the same circumstances because the call to check_signals_nogvl (through sigwait_timeout) in rb_sigwait_sleep returns true if there is any pending signal for the main thread to handle. That then causes rb_sigwait_sleep to skip over sleeping entirely. This is unnescessary and counterproductive, I believe; if the main thread needs to be woken up that is done inline in check_signals_nogvl anyway. See https://bugs.ruby-lang.org/issues/19680
* Add Fiber#kill, similar to Thread#kill. (#7823)Samuel Williams2023-05-181-6/+4
|
* Remove explicit SIGCHLD handling. (#7816)Samuel Williams2023-05-151-1/+1
| | | | | | | | | * Remove unused SIGCHLD handling. * Remove unused `init_sigchld`. * Remove unnecessary `#define RUBY_SIGCHLD (0)`. * Remove unused `SIGCHLD_LOSSY`.
* fix deadlock on `Thread#join`Koichi Sasada2023-04-041-2/+10
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | because of 9720f5ac894566ade2aabcf9adea0a3235de1353 http://rubyci.s3.amazonaws.com/solaris11-sunc/ruby-master/log/20230403T130011Z.fail.html.gz ``` 1) Failure: TestThread#test_signal_at_join [/export/home/chkbuild/chkbuild-sunc/tmp/build/20230403T130011Z/ruby/test/ruby/test_thread.rb:1488]: Exception raised: <#<fatal:"No live threads left. Deadlock?\n1 threads, 1 sleeps current:0x00891288 main thread:0x00891288\n* #<Thread:0xfef89a18 sleep_forever>\n rb_thread_t:0x00891288 native:0x00000001 int:0\n \n">> Backtrace: -:30:in `join' -:30:in `block (3 levels) in <main>' -:21:in `times' -:21:in `block (2 levels) in <main>'. ``` The mechanism: * Main thread (M) calls `Thread#join` * M: calls `sleep_forever()` * M: set `th->status = THREAD_STOPPED_FOREVER` * M: do `checkints` * M: handle a trap handler with `th->status = THREAD_RUNNABLE` * M: thread switch at the end of the trap handler * Another thread (T) will process `Thread#kill` by M. * T: `rb_threadptr_join_list_wakeup()` at the end of T tris to wakeup M, but M's state is runnable because M is handling trap handler and just ignore the waking up and terminate T$a * T: switch to M. * M: after the trap handler, reset `th->status = THREAD_STOPPED_FOREVER` and check deadlock -> Deadlock because only M is living. To avoid such situation, add new sleep flags `SLEEP_ALLOW_SPURIOUS` and `SLEEP_NO_CHECKINTS` to skip any check ints. BTW this is instentional to leave second `vm_check_ints_blocking()` without checking `SLEEP_NO_CHECKINTS` because `SLEEP_ALLOW_SPURIOUS` should be specified with `SLEEP_NO_CHECKINTS` and skipping this checkints can skip any interrupts.
* use `sleep_forever()` on `thread_join_sleep()`Koichi Sasada2023-04-011-7/+10
| | | | because it does same thing.
* cosmetic changeKoichi Sasada2023-03-311-32/+31
| | | | reorder `sleep_forever()` and so on.
* pass `th` to `thread_sched_to_waiting()`Koichi Sasada2023-03-311-5/+5
| | | | for future extension
* remove "\n" for `RUBY_DEBUG_LOG()`Koichi Sasada2023-03-311-1/+1
| | | | because `RUBY_DEBUG_LOG()` add "\n" at the end of message.
* `rb_ractor_thread_list()` only for current ractorKoichi Sasada2023-03-301-1/+1
| | | | so that no need to lock the ractor.
* cosmetic changeKoichi Sasada2023-03-301-11/+16
|
* Rename RB_GC_SAVE_MACHINE_CONTEXT -> RB_VM_SAVE_MACHINE_CONTEXTMatt Valentine-House2023-03-151-3/+3
|
* Remove SIGCHLD `waidpid`. (#7527)Samuel Williams2023-03-151-21/+0
| | | | | | | * Remove `waitpid_lock` and related code. * Remove un-necessary test. * Remove `rb_thread_sleep_interruptible` dead code.
* Revert SIGCHLD changes to diagnose CI failures. (#7517)Samuel Williams2023-03-141-0/+21
| | | | | | | | | | | | | | | * Revert "Remove special handling of `SIGCHLD`. (#7482)" This reverts commit 44a0711eab7fbc71ac2c8ff489d8c53e97a8fe75. * Revert "Remove prototypes for functions that are no longer used. (#7497)" This reverts commit 4dce12bead3bfd91fd80b5e7195f7f540ffffacb. * Revert "Remove SIGCHLD `waidpid`. (#7476)" This reverts commit 1658e7d96696a656d9bd0a0c84c82cde86914ba2. * Fix change to rjit variable name.
* Remove SIGCHLD `waidpid`. (#7476)Samuel Williams2023-03-091-21/+0
| | | | | | | * Remove `waitpid_lock` and related code. * Remove un-necessary test. * Remove `rb_thread_sleep_interruptible` dead code.
* Remove obsoleted functions in rjit.cTakashi Kokubun2023-03-071-3/+0
|
* Get rid of MJIT's special forkTakashi Kokubun2023-03-071-15/+0
|
* s/mjit/rjit/Takashi Kokubun2023-03-061-7/+7
|
* s/MJIT/RJIT/Takashi Kokubun2023-03-061-6/+6
|
* Correctly clean up `keeping_mutexes` before resuming any other threads. (#7460)Samuel Williams2023-03-071-1/+1
| | | | | | | | | | | It's possible (but very rare) to have a race condition between setting `mutex->fiber = NULL` and `thread_mutex_remove(th, mutex)` which results in the following bug: ``` [BUG] invalid keeping_mutexes: Attempt to unlock a mutex which is not locked ``` Fixes <https://bugs.ruby-lang.org/issues/19480>.
* Stop exporting symbols for MJITTakashi Kokubun2023-03-061-1/+1
|
* TestThreadInstrumentation: emit the EXIT event soonerJean Boussier2023-03-061-1/+0
| | | | | | | | | | | | | ``` 1) Failure: TestThreadInstrumentation#test_thread_instrumentation [/tmp/ruby/src/trunk-repeat20-asserts/test/-ext-/thread/test_instrumentation_api.rb:33]: Call counters[4]: [3, 4, 4, 4, 0]. Expected 0 to be > 0. ``` We fire the EXIT hook after the call to `thread_sched_to_dead` which mean another thread might be running before the `EXIT` hook have been executed.
* Merge gc.h and internal/gc.hMatt Valentine-House2023-02-091-1/+1
| | | | [Feature #19425]
* Only emit circular dependency warning for owned thread shieldsJean byroot Boussier2023-02-081-0/+11
| | | | | | | | | | [Bug #19415] If multiple threads attemps to load the same file concurrently it's not a circular dependency issue. So we check that the existing ThreadShield is owner by the current fiber before warning about circular dependencies.
* Revert "Only emit circular dependency warning for owned thread shields"Jean byroot Boussier2023-02-061-11/+0
| | | | This reverts commit fa49651e05a06512e18ccb2f54a7198c9ff579de.
* Only emit circular dependency warning for owned thread shieldsJean Boussier2023-02-061-0/+11
| | | | | | | | | | [Bug #19415] If multiple threads attemps to load the same file concurrently it's not a circular dependency issue. So we check that the existing ThreadShield is owner by the current fiber before warning about circular dependencies.
* Remove unused struct member thgroup->groupMatt Valentine-House2023-01-201-2/+0
|
* Introduce `Fiber#storage` for inheritable fiber-scoped variables. (#6612)Samuel Williams2022-12-011-0/+2
|
* Using UNDEF_P macroS-H-GAMELINKS2022-11-161-8/+8
|
* Make pending_interrupt?(Exception) workYusuke Endoh2022-11-091-1/+1
| | | | | | A patch from katsu (Katsuhiro Ueno) [Bug #19110]
* Avoid missed wakeup with fiber scheduler and Fiber.blocking. (#6588)Samuel Williams2022-10-201-2/+2
| | | * Ensure that blocked fibers don't prevent valid wakeups.
* Add IO#timeout attribute and use it for blocking IO operations. (#5653)Samuel Williams2022-10-071-0/+11
|
* MJIT: Do not hang after forking with threadsTakashi Kokubun2022-09-111-7/+7
| | | | | | | | | | | First, rb_mjit_fork should call rb_thread_atfork to stop threads after fork in the child process. Unfortunately, we cannot use rb_fork_ruby to prevent this kind of mistakes because MJIT needs special handling of waiting_pid and mjit_pause/resume. Second, mjit_waitpid_finished should be checked regardless of trap_interrupt. It doesn't seem like the flag is not set when SIGCHLD is handled for an MJIT child process.
* Exit status macros need sys/wait.h on FreeBSDNobuyoshi Nakada2022-09-071-0/+4
|
* Do not fork the process on --mjit-waitTakashi Kokubun2022-09-061-1/+1
| | | | | fork is for parallel compilation, but --mjit-wait cancels it. It's more useful to not fork it for binding.irb, debugging, etc.
* Allow `RUBY_DEBUG_LOG` format to be emptyNobuyoshi Nakada2022-08-061-5/+5
| | | | | | | GCC warns of empty format strings, perhaps because they have no effects in printf() and there are better ways than sprintf(). However, ruby_debug_log() adds informations other than the format, this warning is not the case.