/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironruby@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Text;
using System.Threading;
using IronRuby.Runtime;
using IronRuby.Runtime.Calls;
using Microsoft.Scripting.Runtime;
namespace IronRuby.Builtins {
///
/// Ruby threads are represented by CLR thread objects (System.Threading.Thread).
///
/// Thread#raise, Thread#kill and friends act on another thread cooperatively: the exception is parked
/// and the target picks it up at its next safe point (see RubyUtils.RaiseAsyncException).
///
[RubyClass("Thread", Extends = typeof(Thread), Inherits = typeof(object))]
public static partial class ThreadOps {
static bool _globalAbortOnException;
static bool _globalReportOnException = true;
///
/// The ThreadState enumeration is a flag, and multiple values could be set simultaneously. Also,
/// there is other state that IronRuby tracks. RubyThreadStatus flattens out the different states
/// into non-overlapping values.
///
private enum RubyThreadStatus {
///
/// Ruby does not expose such a state. However, since IronRuby uses CLR threads, this state can exist for
/// threads that are not created directly from Ruby code
///
Unstarted,
Running,
Sleeping,
Completed,
///
/// If Thread#kill has been called, and the thread is not sleeping
///
Aborting,
///
/// An unhandled exception was thrown by the thread
///
Aborted
}
public class RubyThreadInfo {
// Keyed by the Thread object, not its ManagedThreadId (Largo/ironruby#126): .NET hands a
// dead thread's id to a new thread once the old Thread object has been collected, and the
// new thread must start with an info of its own, not the dead one's locals, name, group
// and fiber flags. The table holds an info only as long as something holds its Thread -
// a running thread is rooted by the runtime, a finished one by whatever Ruby object still
// refers to it (Thread#value, #[] on a dead thread keep working) - so nothing leaks.
private static readonly ConditionalWeakTable _mapping = new ConditionalWeakTable();
// The infos Threads enumerates (ConditionalWeakTable has no cheap enumeration). An entry
// whose thread has finished is pruned here; the info itself stays reachable through
// _mapping for as long as its Thread is. Guarded by _mappingLock.
private static readonly List _registered = new List();
private static readonly object _mappingLock = new object();
private static int _pruneAt = 64;
// Lets the runtime's own native waits (DescriptorStream's poll) report the thread as
// sleeping, the way the waits in this library do by setting Blocked themselves.
static RubyThreadInfo() {
RubyUtils.NativeWaitHook = blocked => {
var info = FromThread(Thread.CurrentThread);
bool was = info._blocked;
info._blocked = blocked;
return was;
};
RubyUtils.ManagedWaitHook = waiting => {
var info = FromThread(Thread.CurrentThread);
bool was = info._inManagedWait;
info._inManagedWait = waiting;
return was;
};
RubyUtils.AsyncExceptionRedirectHook = ForwardToActiveFiber;
}
///
/// An exception parked for this CLR thread while it is not the running fiber of its Ruby
/// thread - it resumed another fiber and waits for it, its fiber is finishing, or it sits
/// in the fiber pool - goes on to the fiber that is running.
///
private static bool ForwardToActiveFiber() {
if (TryForwardToActiveFiber()) {
return true;
}
// A fiber thread outside its fiber keeps it parked: FiberCore.Run picks it up once
// the fiber can take it, and a thread that goes away drops it.
RubyThreadInfo info = FromThread(Thread.CurrentThread);
return info.IsFiberWorker && !info.InFiberRun;
}
///
/// Moves what is parked for this CLR thread to the running fiber of the Ruby thread it
/// runs on behalf of (), if that is another one.
///
internal static bool TryForwardToActiveFiber() {
Thread current = Thread.CurrentThread;
Thread active = FromThread(RubyUtils.CurrentRubyThread).ActiveFiberThread;
return active != null && !ReferenceEquals(active, current) && active.IsAlive && ForwardAsyncException(current, active);
}
/// Moves what is parked for to .
internal static bool ForwardAsyncException(Thread/*!*/ from, Thread/*!*/ to) {
if (!RubyUtils.ForwardAsyncException(from, to)) {
return false;
}
// as RaiseAsyncException does: Kernel#sleep waits on the run signal
FromThread(to).RunForInterrupt();
return true;
}
private readonly Dictionary _threadLocalStorage;
private ThreadGroup _group;
private readonly Thread _thread;
// In a wait a Ruby program can see (RubyUtils.BlockingWait), the only kind Thread#status
// reports as "sleep": a syscall (_blocked), or a managed wait (_inManagedWait), which counts
// once the CLR has the thread in WaitSleepJoin too. Written only by the thread itself.
private volatile bool _blocked;
private volatile bool _inManagedWait;
private bool _abortOnException;
private AutoResetEvent _runSignal = new AutoResetEvent(false);
// Guarded by _sleepLock, which makes "is it sleeping? then wake it" (Run) and "the sleep is
// over; drop a wake-up it did not take" (EndSleep) happen one after the other.
private bool _isSleeping;
// Set by a Run() or Wake() for the current (or, for Wake, the coming) sleep, as opposed to the
// RunForInterrupt that follows a Thread#raise; guarded by _sleepLock, cleared when the sleep ends.
private bool _wokenByRun;
private readonly object/*!*/ _sleepLock = new object();
private RubyThreadInfo(Thread thread) {
_threadLocalStorage = new Dictionary();
_group = ThreadGroup.Default;
_thread = thread;
ReportOnException = _globalReportOnException;
}
// The calling thread's own info. Nearly every lookup is for the current thread - Thread.current,
// Thread#[] on it, Mutex, Monitor - and a thread's entry in _mapping is never replaced while the thread runs, so
// once looked up it can be answered without the global lock.
[ThreadStatic]
private static RubyThreadInfo _current;
internal static RubyThreadInfo FromThread(Thread t) {
RubyThreadInfo current = _current;
if (current != null && ReferenceEquals(current._thread, t)) {
return current;
}
return Lookup(t);
}
/// The info of the calling CLR thread (for a fiber, the fiber's own thread).
internal static RubyThreadInfo Current {
get { return _current ?? Lookup(Thread.CurrentThread); }
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static RubyThreadInfo Lookup(Thread t) {
RubyThreadInfo result;
lock (_mappingLock) {
if (!_mapping.TryGetValue(t, out result)) {
result = new RubyThreadInfo(t);
_mapping.Add(t, result);
_registered.Add(result);
if (_registered.Count >= _pruneAt) {
PruneFinished();
_pruneAt = Math.Max(64, _registered.Count * 2);
}
}
}
if (ReferenceEquals(t, Thread.CurrentThread) && ReferenceEquals(result._thread, t)) {
_current = result;
}
return result;
}
///
/// Drops the infos of threads that have finished from , which would
/// otherwise keep every Thread the process ever made alive. A thread that has not been
/// started yet stays: it is about to run. Caller holds _mappingLock.
///
private static void PruneFinished() {
_registered.RemoveAll(info => (info._thread.ThreadState & System.Threading.ThreadState.Stopped) != 0);
}
///
/// Drops the info of a Ruby thread whose block is over from . Left for the
/// next prune - up to 64 threads later, or twice as many as were alive at the last one - it kept the
/// finished Thread reachable, so the Thread was promoted through the GCs in between and then stayed,
/// with the CLR's record of the dead thread, until a gen-2 collection.
///
internal static void Unregister(RubyThreadInfo/*!*/ info) {
lock (_mappingLock) {
// from the end: a thread that finishes is usually one of the latest
int index = _registered.LastIndexOf(info);
if (index >= 0) {
_registered.RemoveAt(index);
}
}
}
/// Registers the calling thread; cheap once it is.
internal static void RegisterCurrentThread() {
if (_current == null) {
Lookup(Thread.CurrentThread);
}
}
internal object this[RubySymbol/*!*/ key] {
get {
lock (_threadLocalStorage) {
object result;
if (!_threadLocalStorage.TryGetValue(key, out result)) {
result = null;
}
return result;
}
}
set {
lock (_threadLocalStorage) {
if (value == null) {
_threadLocalStorage.Remove(key);
} else {
_threadLocalStorage[key] = value;
}
}
}
}
/// Forgets every fiber-local, for a fiber thread that goes back to the pool.
internal void ClearLocals() {
lock (_threadLocalStorage) {
_threadLocalStorage.Clear();
}
}
internal bool HasKey(RubySymbol/*!*/ key) {
lock (_threadLocalStorage) {
return _threadLocalStorage.ContainsKey(key);
}
}
internal RubyArray GetKeys() {
lock (_threadLocalStorage) {
RubyArray result = new RubyArray(_threadLocalStorage.Count);
foreach (RubySymbol key in _threadLocalStorage.Keys) {
// the runtime's own bookkeeping (the Ruby-level Fiber's) is not the program's
if (!key.ToString().StartsWith("__ir_", StringComparison.Ordinal)) {
result.Add(key);
}
}
return result;
}
}
internal ThreadGroup Group {
get {
return _group;
}
set {
Interlocked.Exchange(ref _group, value);
}
}
internal Thread Thread {
get {
return _thread;
}
}
internal Exception Exception { get; set; }
internal object Result { get; set; }
///
/// The Ractor the thread belongs to: the one that started it, or the one it is the main
/// thread of. Null for the main Ractor's threads.
///
internal RubyRactor Ractor { get; set; }
internal bool CreatedFromRuby { get; set; }
///
/// Set by a thread Ruby created while it runs Ruby code: from just before its block until it has
/// cleaned up after it. Outside that the CLR reports the thread as WaitSleepJoin while it starts
/// up and while it is torn down, where MRI's thread is "run".
///
internal volatile bool RunsRuby;
///
/// The runtime whose Thread.new made this thread; null for a thread Ruby did not create
/// (a host's, the main thread). Each RubyContext is a VM of its own, as far as which
/// threads it has goes.
///
internal RubyContext Context {
get {
RubyContext context;
return (_context != null && _context.TryGetTarget(out context)) ? context : null;
}
set { _context = (value != null) ? new WeakReference(value) : null; }
}
// Weak: an info lives as long as its Thread (the main thread's for good), and a strong
// reference here would keep a runtime the host has let go of alive that long.
private WeakReference _context;
///
/// A CLR thread that has run a fiber of some thread's (ThreadOps.Fiber.cs). It is never a
/// Ruby thread itself, before, between or after its fibers - Thread.current inside a
/// fiber is the thread that owns it - so the Ruby thread lists leave it out for good.
///
internal volatile bool IsFiberWorker;
///
/// The fiber thread is inside FiberCore.Run - its fiber's code, with interrupts masked
/// until the fiber's block runs. Outside it (starting up, between two fibers) a
/// Thread#raise parked for the thread must not be raised there: nothing would catch it.
///
internal volatile bool InFiberRun;
internal bool ExitRequested { get; set; }
internal MutableString Name { get; set; }
internal bool ReportOnException { get; set; }
internal bool IsSleeping { get { return _isSleeping; } }
///
/// The Ruby name of the native blocking call the thread is parked in
/// ("TCPServer#accept"), or null. A thread sitting in a native call has no CLR
/// frame that maps back to a Ruby method, so Thread#backtrace would otherwise stop
/// at the call site; MRI shows the method itself on top. Written only by the thread
/// it describes, read by any thread.
///
internal volatile string BlockedLabel;
///
/// The CLR thread of the fiber this thread is running, for Thread#raise; null before the
/// thread has run a fiber. Changed by the fiber handing control on (FiberCore.MakeRunning),
/// under .
///
internal volatile Thread ActiveFiberThread;
///
/// Makes "find the running fiber and park a Thread#raise for it" (RaiseAsyncException)
/// and "make another fiber the running one and move what is parked" (FiberCore.MakeRunning)
/// happen one after the other: the raise is then either parked before the switch, and
/// travels with control, or after it, for the new fiber - never for the fiber that has
/// just handed control on, which would pass it along only later, when MRI's thread has
/// long raised it.
///
internal readonly object/*!*/ FiberSwitchLock = new object();
internal FiberCore FiberExecution;
///
/// A fiber thread parked in the pool between two fibers (ThreadOps.Fiber.cs). It is no
/// Ruby thread of anybody's while it waits, so the thread lists leave it out.
///
internal volatile bool IsIdleFiberWorker;
///
/// MRI's Thread#priority is a small integer clamped to -3..3 that outlives the thread;
/// the CLR's is a five-valued enum that a dead thread refuses to answer at all. Keep the
/// Ruby value here and treat the CLR priority as a write-only projection of it.
///
internal int Priority { get; set; }
/// "file:line" of the Thread.new call, which MRI puts in Thread#inspect.
internal string Location { get; set; }
///
/// Set while a thread of a Thread subclass is between allocation and the Thread#initialize
/// (called by the subclass's #initialize through super) that starts it.
///
internal ThreadStarter Starter { get; set; }
// Thread#[] is fiber-local in MRI (and, since every fiber is its own CLR thread here, the
// dictionary above already is); Thread#thread_variable_get is thread-local, so it needs
// storage of its own.
private readonly Dictionary _threadVariables = new Dictionary();
internal object GetThreadVariable(RubySymbol/*!*/ key) {
lock (_threadVariables) {
object result;
return _threadVariables.TryGetValue(key, out result) ? result : null;
}
}
internal void SetThreadVariable(RubySymbol/*!*/ key, object value) {
lock (_threadVariables) {
if (value == null) {
_threadVariables.Remove(key);
} else {
_threadVariables[key] = value;
}
}
}
internal bool HasThreadVariable(RubySymbol/*!*/ key) {
lock (_threadVariables) {
return _threadVariables.ContainsKey(key);
}
}
internal RubyArray/*!*/ GetThreadVariableKeys() {
lock (_threadVariables) {
RubyArray result = new RubyArray(_threadVariables.Count);
foreach (RubySymbol key in _threadVariables.Keys) {
result.Add(key);
}
return result;
}
}
internal bool InManagedWait {
get { return _inManagedWait; }
}
internal bool Blocked {
get {
return _blocked;
}
set {
System.Diagnostics.Debug.Assert(Thread.CurrentThread == _thread);
_blocked = value;
}
}
internal bool AbortOnException {
get {
return _abortOnException;
}
set {
_abortOnException = value;
}
}
internal static RubyThreadInfo[] Threads {
get {
lock (_mappingLock) {
PruneFinished();
List result = new List(_registered.Count);
foreach (RubyThreadInfo info in _registered) {
if (info.Thread.IsAlive && !info.IsIdleFiberWorker) {
result.Add(info);
}
}
return result.ToArray();
}
}
}
///
/// The Ruby threads of a runtime, as Thread.list and ThreadGroup#list see them:
/// less the threads of another runtime - two ScriptRuntimes in one
/// process are two VMs, and neither lists the other's threads - and less the CLR threads
/// that run (or have run, or hold suspended) a fiber of a thread's. A fiber
/// has a CLR thread of its own here, but in MRI it is part of the thread that owns it, and
/// Thread.current inside it is that thread.
///
internal static RubyThreadInfo[]/*!*/ GetRubyThreads(RubyContext/*!*/ context) {
// The runtime's main thread counts even when no Ruby code has run on it yet
// (a host that creates the runtime on one thread and runs Ruby on another).
Thread main = context.MainThread;
if (main != null && main.IsAlive) {
FromThread(main);
}
RubyThreadInfo[] all = Threads;
var result = new List(all.Length);
foreach (RubyThreadInfo info in all) {
if (info.IsFiberWorker) {
continue;
}
// The runtime's main thread is always its own, even when another runtime's Thread.new
// made it; any other thread belongs to the runtime that made it, or, made by none (a
// host's), to the one asking from it now.
RubyContext owner = info.Context;
if (info.Thread != context.MainThread && (owner != null ? owner != context : info.Thread != Thread.CurrentThread)) {
continue;
}
FiberCore fiber = info.FiberExecution;
if (fiber == null || fiber.Owner == info.Thread) {
result.Add(info);
}
}
return result.ToArray();
}
///
/// The Ruby threads of the Ractor the current thread belongs to: what Thread.list and
/// ThreadGroup#list answer, which in MRI list only the asking Ractor's living threads.
///
internal static RubyThreadInfo[]/*!*/ GetRactorThreads(RubyContext/*!*/ context) {
var ractor = Current.Ractor;
return Array.FindAll(GetRubyThreads(context), info => info.Ractor == ractor);
}
///
/// We do not use Thread.Sleep here as another thread can call Thread#wakeup/Thread#run. Instead, we use our own
/// lock which can be signalled from another thread.
///
internal void Sleep() {
// A Thread#kill/#raise that landed just before we got here parked its exception but
// could not interrupt us - we were not waiting yet. Deliver it instead of sleeping
// on, which would never end.
RubyUtils.CheckAsyncException();
bool wasWaiting = _inManagedWait;
bool wasSleeping = BeginSleep();
try {
// One parked since that look found no sleep to end (RunForInterrupt); one parked
// from now on does.
RubyUtils.CheckAsyncException();
do {
_inManagedWait = true;
try {
_runSignal.WaitOne();
} catch (ThreadInterruptedException) {
// Thread#kill / Thread#raise nudged us: deliver the parked exception. If there is none
// the interrupt was spurious and the sleep simply ends (MRI's sleep is also allowed to
// return early). The RunForInterrupt that follows the interrupt finds the exception
// still parked or not: if it does, the end of the sleep drops its wake-up.
_inManagedWait = wasWaiting;
RubyUtils.TranslateThreadInterrupt();
}
} while (WokenForMaskedInterrupt());
} finally {
EndSleep(wasSleeping);
_inManagedWait = wasWaiting;
}
}
///
/// Same as Sleep() but with a timeout (or Timeout.Infinite); returns false if the full timeout
/// elapsed (or an interrupt ended the sleep with nothing to deliver), true if it was woken.
///
internal bool Sleep(int milliseconds) {
RubyUtils.CheckAsyncException();
bool wasWaiting = _inManagedWait;
bool wasSleeping = BeginSleep();
try {
RubyUtils.CheckAsyncException();
long deadline = Environment.TickCount64 + milliseconds;
while (true) {
_inManagedWait = true;
bool woken;
try {
woken = _runSignal.WaitOne(milliseconds);
if (!woken) {
return false;
}
} catch (ThreadInterruptedException) {
_inManagedWait = wasWaiting;
RubyUtils.TranslateThreadInterrupt();
woken = false;
}
if (!WokenForMaskedInterrupt()) {
return woken;
}
if (milliseconds != Timeout.Infinite) {
milliseconds = (int)Math.Max(0, deadline - Environment.TickCount64);
}
}
} finally {
EndSleep(wasSleeping);
_inManagedWait = wasWaiting;
}
}
// Answers whether the thread was sleeping already: a trap handler run by a sleep's safe point
// may sleep in its turn.
private bool BeginSleep() {
using (new RubyUtils.UninterruptedLock(_sleepLock)) {
bool wasSleeping = _isSleeping;
_isSleeping = true;
return wasSleeping;
}
}
///
/// Whether the wait that has just ended was ended for nothing but a Thread#raise that a
/// Thread.handle_interrupt mask holds back, so that the sleep goes on: MRI's sleep_forever and
/// sleep_hrtime check interrupts and sleep again while the thread is still meant to sleep, and a
/// masked exception stays queued (Thread.pending_interrupt? is true) rather than ending
/// Thread.stop or sleep. A Thread#run or #wakeup ends the sleep as always.
///
private bool WokenForMaskedInterrupt() {
// throws what may be delivered here and now
RubyUtils.CheckAsyncException();
using (new RubyUtils.UninterruptedLock(_sleepLock)) {
if (_wokenByRun) {
return false;
}
if (!RubyUtils.HasPendingAsyncException(_thread)) {
return false;
}
// drop the RunForInterrupt wake-up, if it has not been taken, or the next wait ends at once
_runSignal.Reset();
}
// A raise that may be delivered and was parked since the look above has had its wake-up
// dropped by that Reset, if its RunForInterrupt came first: take it now rather than wait
// for a wake-up that has come and gone. One parked after the Reset sets the signal again.
RubyUtils.CheckAsyncException();
return true;
}
///
/// Ends a sleep, and drops a Run() it did not take. Thread#raise and Thread#kill interrupt
/// the thread and then Run() it, for a sleep the interrupt cannot reach yet; a Run() that
/// came after the interrupt had ended the sleep stayed latched, and the thread's next sleep
/// returned at once - for a fiber thread from the pool, the sleep of another thread's fiber.
/// MRI's Thread#wakeup only wakes a thread that is sleeping, and a later sleep is not cut
/// short by it either.
///
private void EndSleep(bool wasSleeping) {
using (new RubyUtils.UninterruptedLock(_sleepLock)) {
_isSleeping = wasSleeping;
if (!wasSleeping) {
_runSignal.Reset();
_wokenByRun = false;
}
}
}
internal void Run() {
using (new RubyUtils.UninterruptedLock(_sleepLock)) {
if (_isSleeping) {
_wokenByRun = true;
_runSignal.Set();
}
}
}
///
/// The Run() that follows a Thread#raise / Thread#kill parked for this thread, for a sleep the
/// interrupt could not reach (RubyUtils.NudgeThread interrupts only a thread that is already
/// waiting). Only while the exception is still parked: once the thread has taken it, the
/// sleep it ended is over, and a sleep the thread has gone into since - after rescuing the
/// exception - is not this raise's to end.
///
internal void RunForInterrupt() {
using (new RubyUtils.UninterruptedLock(_sleepLock)) {
if (_isSleeping && RubyUtils.HasPendingAsyncException(_thread)) {
_runSignal.Set();
}
}
}
///
/// Like Run(), but signals even if the thread has not reached its wait yet. ConditionVariable
/// registers a waiter before it releases the mutex, so a #signal can arrive first.
///
internal void Wake() {
using (new RubyUtils.UninterruptedLock(_sleepLock)) {
_wokenByRun = true;
}
_runSignal.Set();
}
///
/// Drops a Wake() the thread's sleep did not consume - one that came after a timeout ran
/// out or an exception ended the wait - so that it does not cut the next sleep short.
///
internal void ClearWake() {
using (new RubyUtils.UninterruptedLock(_sleepLock)) {
_wokenByRun = false;
}
_runSignal.Reset();
}
}
// declared private instance methods:
// initialize
// declared protected instance methods:
// declared public instance methods:
private static Exception MakeKeyTypeException(RubyContext/*!*/ context, object key) {
return RubyExceptions.CreateTypeError("{0} is not a symbol nor a string", context.Inspect(key).ToString());
}
///
/// Thread-local keys are Symbols; a String is interned and anything else is given a chance to
/// convert itself with #to_str (but never #to_sym, which MRI is explicit about).
///
private static RubySymbol/*!*/ ToKey(ConversionStorage/*!*/ toStr, RubyContext/*!*/ context, object key) {
RubySymbol symbol = key as RubySymbol;
if (symbol != null) {
return symbol;
}
MutableString str = key as MutableString;
if (str == null && key != null) {
str = Protocols.TryCastToString(toStr, key);
}
if (str == null) {
throw MakeKeyTypeException(context, key);
}
return context.CreateSymbol(str);
}
///
/// Thread#[] and friends are fiber-local in MRI. Every fiber runs on its own CLR thread
/// here, so "the current fiber's storage" is the current CLR thread's - which stopped
/// being the same object as Thread.current when Thread.current started answering the
/// fiber's owning thread. Another thread is addressed by its own storage, as in MRI,
/// where it is that thread's root fiber's.
///
private static RubyThreadInfo/*!*/ FiberLocals(Thread/*!*/ self) {
return self == RubyUtils.CurrentRubyThread ? RubyThreadInfo.Current : RubyThreadInfo.FromThread(self);
}
[RubyMethod("[]")]
public static object GetElement(Thread/*!*/ self, [NotNull]RubySymbol/*!*/ key) {
return FiberLocals(self)[key];
}
[RubyMethod("[]")]
public static object GetElement(RubyContext/*!*/ context, Thread/*!*/ self, [NotNull]MutableString/*!*/ key) {
return GetElement(self, context.CreateSymbol(key));
}
[RubyMethod("[]")]
public static object GetElement(ConversionStorage/*!*/ toStr, RubyContext/*!*/ context, Thread/*!*/ self, object key) {
return GetElement(self, ToKey(toStr, context, key));
}
///
/// Freezing a Thread freezes its local storage: MRI raises FrozenError with a message about
/// the locals rather than about the thread object.
///
private static void CheckLocalsNotFrozen(RubyContext/*!*/ context, Thread/*!*/ self) {
if (context.IsObjectFrozen(self)) {
throw new FrozenError("can't modify frozen thread locals").SetReceiver(self);
}
}
[RubyMethod("[]=")]
public static object SetElement(RubyContext/*!*/ context, Thread/*!*/ self, [NotNull]RubySymbol/*!*/ key, object value) {
CheckLocalsNotFrozen(context, self);
FiberLocals(self)[key] = value;
return value;
}
[RubyMethod("[]=")]
public static object SetElement(RubyContext/*!*/ context, Thread/*!*/ self, [NotNull]MutableString/*!*/ key, object value) {
return SetElement(context, self, context.CreateSymbol(key), value);
}
[RubyMethod("[]=")]
public static object SetElement(ConversionStorage/*!*/ toStr, RubyContext/*!*/ context, Thread/*!*/ self, object key, object value) {
return SetElement(context, self, ToKey(toStr, context, key), value);
}
[RubyMethod("abort_on_exception")]
public static object AbortOnException(Thread/*!*/ self) {
RubyThreadInfo info = RubyThreadInfo.FromThread(self);
return info.AbortOnException;
}
[RubyMethod("abort_on_exception=")]
public static object AbortOnException(Thread/*!*/ self, bool value) {
RubyThreadInfo info = RubyThreadInfo.FromThread(self);
info.AbortOnException = value;
return value;
}
[RubyMethod("alive?")]
public static bool IsAlive(Thread/*!*/ self) {
RubyThreadInfo.RegisterCurrentThread();
return self.IsAlive;
}
///
/// The Ruby stack of this thread, or nil if there is none to report. Thread#backtrace is
/// defined in Ruby on top of this so that it can do MRI's start/length slicing; this is only
/// the part that has to reach into the runtime.
///
/// A thread that has not started or has already finished has no stack and answers nil, as in
/// MRI. A running thread answers a snapshot: it does not stop to be read, so by the time the
/// array is handed back the thread has probably moved on.
///
[RubyMethod("__native_backtrace__", RubyMethodAttributes.PrivateInstance)]
public static object NativeBacktrace(RubyContext/*!*/ context, Thread/*!*/ self) {
RubyThreadInfo.RegisterCurrentThread();
if (!self.IsAlive) {
return null;
}
RubyArray trace = RubyExceptionData.CreateBacktrace(context, self);
RubyThreadInfo info = RubyThreadInfo.FromThread(self);
string blockedIn = info.IsSleeping ? "Kernel#sleep" : info.BlockedLabel;
if (trace != null && trace.Count > 0 && blockedIn != null) {
string caller = trace[0].ToString();
int label = caller.LastIndexOf(":in ", StringComparison.Ordinal);
if (label >= 0) {
caller = caller.Substring(0, label);
}
// the frame of the core method written in Ruby that the thread is blocked in (the prelude's Kernel#sleep)
// has its label already
string blockedFrame = caller + ":in '" + blockedIn + "'";
if (trace[0].ToString() != blockedFrame) {
trace.Insert(0, MutableString.CreateMutable(blockedFrame, RubyEncoding.UTF8));
}
}
return trace;
}
[RubyMethod("group")]
public static ThreadGroup Group(Thread/*!*/ self) {
RubyThreadInfo info = RubyThreadInfo.FromThread(self);
return info.Group;
}
///
/// MRI: "#<Thread:0x... file:line status>", with "@name" after the id when the thread has
/// one. The string is BINARY unless a name forces a wider encoding, because the file name
/// is a path and paths have no encoding of their own.
///
[RubyMethod("inspect")]
[RubyMethod("to_s")]
public static MutableString/*!*/ Inspect(RubyContext/*!*/ context, Thread/*!*/ self) {
RubyThreadInfo.RegisterCurrentThread();
MutableString result = MutableString.CreateMutable(RubyEncoding.Binary);
result.Append("#<");
// The class is the one the thread was made by, a Thread subclass's included (the CLR thread is
// adopted by it), and a name that is not ASCII makes the answer UTF-8, as the name of a thread does.
result.Append(MutableString.Create(context.GetClassOf(self).GetNonNullName(context), RubyEncoding.UTF8));
result.Append(':');
RubyUtils.AppendFormatHexObjectId(result, RubyUtils.GetObjectId(context, self));
RubyThreadInfo selfInfo = RubyThreadInfo.FromThread(self);
MutableString name = selfInfo.Name;
if (name != null) {
result.Append('@');
result.Append(name);
}
if (selfInfo.Location != null) {
result.Append(' ');
result.Append(selfInfo.Location);
}
result.Append(' ');
RubyThreadStatus status = GetStatus(self);
switch (status) {
case RubyThreadStatus.Unstarted:
result.Append("unstarted");
break;
case RubyThreadStatus.Running:
result.Append("run");
break;
case RubyThreadStatus.Sleeping:
result.Append("sleep");
break;
case RubyThreadStatus.Aborting:
result.Append("aborting");
break;
case RubyThreadStatus.Completed:
case RubyThreadStatus.Aborted:
result.Append("dead");
break;
}
result.Append('>');
return result;
}
// How long one wait inside Thread#join lasts before the joining thread reaches a safe point.
private const int JoinSliceMilliseconds = 20;
///
/// Joins in slices rather than in one CLR Thread.Join. A signal is delivered by running its
/// trap handler on the main thread at a safe point, and a thread parked in Thread.Join has
/// none: `trap("TERM") { ... }; server_thread.join` - which is how puma's single mode, and
/// most servers, wait - never ran its handler, so the process ignored SIGTERM and SIGINT.
/// Answers whether the thread finished within .
///
private static bool JoinWithSafePoints(Thread/*!*/ self, int timeout) {
long deadline = (timeout == Timeout.Infinite) ? Int64.MaxValue : Environment.TickCount64 + timeout;
while (true) {
try {
long remaining = deadline - Environment.TickCount64;
int slice = (int)Math.Max(0, Math.Min(remaining, JoinSliceMilliseconds));
bool joined;
using (RubyUtils.BlockingWait.Enter()) {
joined = self.Join(slice);
}
if (joined) {
return true;
}
if (remaining <= JoinSliceMilliseconds) {
return false;
}
RubyUtils.CheckAsyncException();
} catch (ThreadInterruptedException) {
RubyUtils.TranslateThreadInterrupt();
}
}
}
[RubyMethod("join")]
public static Thread/*!*/ Join(RubyContext/*!*/ context, Thread/*!*/ self) {
RubyThreadInfo.RegisterCurrentThread();
RequireOtherThread(context, self);
JoinWithSafePoints(self, Timeout.Infinite);
Exception threadException = RubyThreadInfo.FromThread(self).Exception;
if (threadException != null) {
throw threadException;
}
return self;
}
///
/// Thread#join(timeout). A nil timeout means "no timeout", so it cannot go through the
/// Float conversion the other values do.
///
[RubyMethod("join")]
public static Thread Join(ConversionStorage/*!*/ floatConversion, RubyContext/*!*/ context, Thread/*!*/ self, object timeout) {
if (timeout == null) {
return Join(context, self);
}
// MRI's rb_num2dbl, not Float(): any Integer (2**62 is a long here) or Float as it is, a String,
// true or false a TypeError rather than the ArgumentError that Float("bar") would raise, and
// anything else - a Rational, an object with #to_f - through #to_f.
double seconds;
if (timeout is int) {
seconds = (int)timeout;
} else if (timeout is double) {
seconds = (double)timeout;
} else if (timeout is long) {
seconds = (long)timeout;
} else if (timeout is System.Numerics.BigInteger) {
seconds = (double)(System.Numerics.BigInteger)timeout;
} else if (timeout is MutableString || timeout is bool) {
throw RubyExceptions.CreateTypeError("no implicit conversion to float from {0}",
timeout is bool ? ((bool)timeout ? "true" : "false") : "string");
} else {
seconds = Protocols.CastToFloat(floatConversion, timeout);
}
return Join(context, self, seconds);
}
// A thread cannot wait for itself, it would never wake up; and nothing waits for the main
// thread, whose end is the end of the program.
private static void RequireOtherThread(RubyContext/*!*/ context, Thread/*!*/ self) {
if (ReferenceEquals(self, Thread.CurrentThread)) {
throw new ThreadError("Target thread must not be current thread");
}
if (ReferenceEquals(self, context.MainThread)) {
throw new ThreadError("Target thread must not be main thread");
}
}
public static Thread/*!*/ Join(RubyContext/*!*/ context, Thread/*!*/ self, double seconds) {
RubyThreadInfo.RegisterCurrentThread();
RequireOtherThread(context, self);
if (!(self.ThreadState == ThreadState.AbortRequested || self.ThreadState == ThreadState.Aborted)) {
// a negative limit, -Float::INFINITY included, does not wait at all (MRI's thread_join
// with a limit of 0); one past what a wait can take is no limit
double ms = seconds * 1000;
int timeout = (ms <= 0 || Double.IsNaN(ms)) ? 0 : ms > Int32.MaxValue ? Timeout.Infinite : (int)ms;
bool joined = JoinWithSafePoints(self, timeout);
if (!joined) {
return null;
}
}
Exception threadException = RubyThreadInfo.FromThread(self).Exception;
if (threadException != null) {
throw threadException;
}
return self;
}
///
/// MRI's rb_thread_kill: killing the main thread - from itself or from any other - is exit(0) in the
/// thread that asks, a SystemExit that runs the ensure clauses and at_exit handlers and ends the
/// program with status 0, rather than the unwinding of a thread that nothing would report.
///
[RubyMethod("kill")]
[RubyMethod("exit")]
[RubyMethod("terminate")]
public static Thread Kill(RubyContext/*!*/ context, Thread/*!*/ self) {
if (ReferenceEquals(self, context.MainThread) && self.IsAlive && !RubyThreadInfo.FromThread(self).ExitRequested) {
throw new SystemExit(0, "exit");
}
return Kill(self);
}
public static Thread Kill(Thread/*!*/ self) {
RubyThreadInfo.RegisterCurrentThread();
RubyThreadInfo info = RubyThreadInfo.FromThread(self);
if (!self.IsAlive) {
return self;
}
if (GetStatus(self) == RubyThreadStatus.Sleeping && info.ExitRequested) {
// Thread must be sleeping in an ensure clause. Wake up the thread and allow ensure clause to complete
info.Run();
return self;
}
info.ExitRequested = true;
if (self == Thread.CurrentThread) {
// No need for the asynchronous machinery - just start unwinding.
throw new RubyUtils.ThreadExitSignal();
}
RubyUtils.ExitThread(self);
info.RunForInterrupt();
return self;
}
[RubyMethod("key?")]
public static object HasKey(Thread/*!*/ self, [NotNull]RubySymbol/*!*/ key) {
return FiberLocals(self).HasKey(key);
}
[RubyMethod("key?")]
public static object HasKey(RubyContext/*!*/ context, Thread/*!*/ self, [NotNull]MutableString/*!*/ key) {
return HasKey(self, context.CreateSymbol(key));
}
[RubyMethod("key?")]
public static object HasKey(ConversionStorage/*!*/ toStr, RubyContext/*!*/ context, Thread/*!*/ self, object key) {
return HasKey(self, ToKey(toStr, context, key));
}
[RubyMethod("keys")]
public static object Keys(RubyContext/*!*/ context, Thread/*!*/ self) {
return FiberLocals(self).GetKeys();
}
#region priority, priority=
[RubyMethod("priority")]
public static object Priority(Thread/*!*/ self) {
RubyThreadInfo.RegisterCurrentThread();
return RubyThreadInfo.FromThread(self).Priority;
}
[RubyMethod("priority=")]
public static object Priority(Thread/*!*/ self, [DefaultProtocol]int priority) {
RubyThreadInfo.RegisterCurrentThread();
// MRI clamps to -3..3 and reports back the clamped value.
int clamped = priority < -3 ? -3 : (priority > 3 ? 3 : priority);
RubyThreadInfo.FromThread(self).Priority = clamped;
try {
if (clamped <= -2) {
self.Priority = ThreadPriority.Lowest;
} else if (clamped == -1) {
self.Priority = ThreadPriority.BelowNormal;
} else if (clamped == 0) {
self.Priority = ThreadPriority.Normal;
} else if (clamped == 1) {
self.Priority = ThreadPriority.AboveNormal;
} else {
self.Priority = ThreadPriority.Highest;
}
} catch (ThreadStateException) {
// The thread has already finished. MRI still remembers the value, so we do too;
// there is simply nothing left to apply it to.
}
return priority;
}
#endregion
#region raise, fail
private static void RaiseAsyncException(RubyContext/*!*/ context, Thread thread, Exception exception) {
// MRI delivers the interrupt to the thread's running fiber, and each fiber here is a
// CLR thread of its own.
RubyThreadInfo ownerInfo = RubyThreadInfo.FromThread(thread);
Thread owner = thread;
// rb_threadptr_raise does nothing to a dead thread. Parked, the exception would keep
// the thread's safe point requested for good and pending_interrupt? true. A thread
// still running its ensure clauses after a kill is not dead yet.
RubyThreadStatus ownerStatus = GetStatus(owner);
if (ownerStatus == RubyThreadStatus.Completed || ownerStatus == RubyThreadStatus.Aborted) {
return;
}
RubyThreadInfo info;
RubyThreadStatus status;
using (new RubyUtils.UninterruptedLock(ownerInfo.FiberSwitchLock)) {
Thread activeFiber = ownerInfo.ActiveFiberThread;
if (activeFiber != null && activeFiber.IsAlive) {
thread = activeFiber;
}
// A raise behind a Thread#kill that has not reached the thread yet is dropped: MRI's
// rb_threadptr_to_kill clears the interrupts queued behind the kill when it takes it.
// Parked, the raise would replace the kill. Once the kill has been taken and the thread
// is running its ensure clauses ("aborting"), a raise is delivered there as anywhere,
// wakes a sleep, and the thread dies of it unless it is rescued (test_thread's
// test_thread_status_raise_after_kill).
if (ownerInfo.ExitRequested && (RubyUtils.IsKillPending(owner) || RubyUtils.IsKillPending(thread))) {
return;
}
info = RubyThreadInfo.FromThread(thread);
status = GetStatus(thread);
if (thread == Thread.CurrentThread) {
throw exception;
}
// rethrow semantics, preserves the backtrace associated with the exception:
RubyUtils.ParkAsyncException(thread, exception, e => {
// MRI raises exception.exception in the target thread
var site = context.GetOrCreateSendSite>("exception", RubyCallSignature.WithImplicitSelf(0));
return site.Target(site, e) as Exception;
});
}
// Not under the lock: the thread may be waiting for it, and an interrupt would break that
// wait off (RubyUtils.ParkAsyncException).
RubyUtils.NudgeThread(thread);
// Kernel#sleep and Thread.stop use the Ruby run signal. This is race-safe even when
// the target has announced sleep but has not entered WaitOne yet.
info.RunForInterrupt();
}
///
/// Thread#raise takes exactly the arguments Kernel#raise does, including `cause:`, and is
/// built from the same helper so the two cannot drift apart.
///
/// The cause is resolved in the *calling* thread's context, which is what MRI 4.0 does:
/// the exception carries the cause of whoever raised it, not of the thread it lands in.
///
[RubyMethod("raise")]
[RubyStackTraceHidden]
[ReceivesKeywords]
public static void RaiseException(RespondToStorage/*!*/ respondToStorage, UnaryOpStorage/*!*/ storage0, BinaryOpStorage/*!*/ storage1,
CallSiteStorage>/*!*/ setBackTraceStorage,
RubyContext/*!*/ context, Thread/*!*/ self, params object[]/*!*/ args) {
// A bare Thread#raise is a plain RuntimeError even on the current thread: unlike
// Kernel#raise it does not re-raise $!, and on another thread MRI cannot see that
// thread's $! anyway.
Exception e = KernelOps.CreateExceptionToRaise(respondToStorage, storage0, storage1, setBackTraceStorage, context, args, false);
// Inside a fiber the current Ruby thread is the fiber's owner; raising on it means
// raising here, not nudging the thread the fiber was started from. MRI's rb_threadptr_raise
// queues the exception on the current thread as on any other and checks for interrupts at once,
// so a Thread.handle_interrupt mask holds it back here too: until the next blocking operation
// under :on_blocking, until the mask is gone under :never.
if (self == RubyUtils.CurrentRubyThread) {
if (RubyUtils.GetInterruptTiming(e) == RubyUtils.InterruptImmediate) {
throw e;
}
RubyUtils.ParkAsyncException(Thread.CurrentThread, e);
return;
}
RaiseAsyncException(context, self, e);
}
#endregion
// safe_level
// TODO: these two methods interrupt a sleeping thread via the Thread.Interrupt API.
// Unfortunately, this API interrupts the sleeping thread by throwing a ThreadInterruptedException.
// In many Ruby programs (eg the specs) this causes the thread to terminate, which is NOT the
// expected behavior. This is tracked by Rubyforge bug # 21157
[RubyMethod("run")]
[RubyMethod("wakeup")]
public static Thread Run(Thread/*!*/ self) {
RubyThreadInfo.RegisterCurrentThread();
if (!self.IsAlive) {
throw new ThreadError("killed thread");
}
RubyThreadInfo info = RubyThreadInfo.FromThread(self);
info.Run();
RubyUtils.UnblockNative(self);
return self;
}
private static RubyThreadStatus GetStatus(Thread thread) {
ThreadState state = thread.ThreadState;
RubyThreadInfo info = RubyThreadInfo.FromThread(thread);
if ((state & ThreadState.Unstarted) == ThreadState.Unstarted) {
if (info.CreatedFromRuby) {
// Ruby threads do not have an unstarted status. We must be in the tiny window when ThreadOps.CreateThread
// created the thread, but has not called Thread.Start on it yet.
return RubyThreadStatus.Running;
} else {
// This is a thread created from outside Ruby. In such a case, we do not know when Thread.Start
// will be called on it. So we report it as unstarted.
return RubyThreadStatus.Unstarted;
}
}
if ((state & (ThreadState.Stopped|ThreadState.Aborted)) != 0) {
if (RubyThreadInfo.FromThread(thread).Exception == null) {
return RubyThreadStatus.Completed;
} else {
return RubyThreadStatus.Aborted;
}
}
// "sleep" is a wait the program can see - Kernel#sleep, a held Mutex, Queue#pop, Thread#join,
// a blocking read - which marks the thread for its duration (RubyUtils.BlockingWait).
// WaitSleepJoin alone is no guide: it also covers every brief wait for an internal lock and
// the handshakes of thread start-up, through which MRI's thread is "run", and a thread that
// looked asleep there made `should_not block_caller` fail at random under load.
// A thread running a fiber does so on the fiber's CLR thread, its own waiting for control
// to come back: it is as blocked as that fiber is.
if (IsBlocked(thread, info)) {
return RubyThreadStatus.Sleeping;
}
if ((state & ThreadState.AbortRequested) != 0) {
return RubyThreadStatus.Aborting;
}
// Thread#kill has been called and the thread is still winding its ensure blocks down.
// MRI reports "aborting" for exactly that window; it is not a CLR thread state, so it
// has to come from the exit flag we set in Kill.
if (info.ExitRequested) {
return RubyThreadStatus.Aborting;
}
// Running, or WaitSleepJoin in a wait that is not the program's
return RubyThreadStatus.Running;
}
private static bool IsBlocked(Thread/*!*/ thread, RubyThreadInfo/*!*/ info) {
Thread fiber = info.ActiveFiberThread;
if (fiber != null && !ReferenceEquals(fiber, thread) && fiber.IsAlive) {
thread = fiber;
info = RubyThreadInfo.FromThread(fiber);
}
if (info.Blocked) {
return true;
}
// The mark first, then the CLR state: a thread that has marked itself but not reached its
// wait yet is not "sleep", for Thread#kill interrupts only a thread that is waiting
// (RubyUtils.NudgeThread), and the spec that sees "sleep" goes on to kill it.
return info.InManagedWait && (thread.ThreadState & ThreadState.WaitSleepJoin) != 0;
}
[RubyMethod("status")]
public static object Status(Thread/*!*/ self) {
RubyThreadInfo.RegisterCurrentThread();
switch (GetStatus(self)) {
case RubyThreadStatus.Unstarted:
return MutableString.CreateAscii("unstarted");
case RubyThreadStatus.Running:
return MutableString.CreateAscii("run");
case RubyThreadStatus.Sleeping:
return MutableString.CreateAscii("sleep");
case RubyThreadStatus.Aborting:
return MutableString.CreateAscii("aborting");
case RubyThreadStatus.Completed:
return false;
case RubyThreadStatus.Aborted:
return null;
default:
throw new ArgumentException("unknown thread status");
}
}
[RubyMethod("value")]
public static object Value(RubyContext/*!*/ context, Thread/*!*/ self) {
Join(context, self);
return RubyThreadInfo.FromThread(self).Result;
}
// stop?
// declared singleton methods
[RubyMethod("abort_on_exception", RubyMethodAttributes.PublicSingleton)]
public static object GlobalAbortOnException(object self) {
return _globalAbortOnException;
}
[RubyMethod("abort_on_exception=", RubyMethodAttributes.PublicSingleton)]
public static object GlobalAbortOnException(object self, bool value) {
_globalAbortOnException = value;
return value;
}
///
/// Every fiber runs on its own CLR thread here, but Ruby says a fiber belongs to the
/// thread that created it - so inside a fiber this answers that thread, not the one the
/// fiber happens to be running on.
///
[RubyMethod("current", RubyMethodAttributes.PublicSingleton)]
public static Thread/*!*/ Current(object self) {
RubyThreadInfo.RegisterCurrentThread();
return RubyUtils.CurrentRubyThread;
}
// exclusive
// fork
[RubyMethod("list", RubyMethodAttributes.PublicSingleton)]
public static RubyArray/*!*/ List(RubyContext/*!*/ context, object self) {
RubyThreadInfo.RegisterCurrentThread();
RubyThreadInfo[] threads = RubyThreadInfo.GetRactorThreads(context);
RubyArray result = new RubyArray(threads.Length);
foreach (RubyThreadInfo threadInfo in threads) {
Thread thread = threadInfo.Thread;
if (thread != null) {
result.Add(thread);
}
}
return result;
}
[RubyMethod("main", RubyMethodAttributes.PublicSingleton)]
public static Thread/*!*/ GetMainThread(RubyContext/*!*/ context, RubyClass self) {
// in a Ractor, the Ractor's own main thread, as in MRI
var ractor = RubyThreadInfo.Current.Ractor;
return (ractor != null && ractor.MainThread != null) ? ractor.MainThread : context.MainThread;
}
[RubyMethod("new", RubyMethodAttributes.PublicSingleton)]
[ReceivesKeywords]
public static Thread/*!*/ CreateThread(CallSiteStorage>/*!*/ storage,
BlockParam startRoutine, object self, params object[]/*!*/ args) {
RubyContext context = storage.Context;
RubyClass cls = self as RubyClass;
if (cls == null || !cls.IsRubyClass) {
// Thread itself: its #initialize is the one that starts the thread, so skip the call.
if (startRoutine == null) {
throw new ThreadError("must be called with a block");
}
return StartThread(context, null, startRoutine, args);
}
// A Thread subclass: its #initialize decides the block (calling super with one), and the
// thread starts in Thread#initialize.
ThreadStarter starter;
Thread result = AllocateThread(context, cls, out starter);
RubyThreadInfo info = RubyThreadInfo.FromThread(result);
info.Starter = starter;
var initialize = storage.GetCallSite("initialize",
new RubyCallSignature(0, RubyCallFlags.HasImplicitSelf | RubyCallFlags.HasSplattedArgument | RubyCallFlags.HasBlock));
initialize.Target(initialize, result, startRoutine != null ? startRoutine.Proc : null, RubyOps.MakeArrayN(args));
if (info.Starter != null) {
info.Starter = null;
throw new ThreadError(String.Format("uninitialized thread - check '{0}#initialize'", cls.GetDisplayName(context, false)));
}
return result;
}
// Thread.start and Thread.fork bypass #initialize; without a block they fail the way
// building a Proc without one does, not the way Thread.new does.
[RubyMethod("start", RubyMethodAttributes.PublicSingleton)]
[RubyMethod("fork", RubyMethodAttributes.PublicSingleton)]
[ReceivesKeywords]
public static Thread/*!*/ StartThread(RubyContext/*!*/ context, BlockParam startRoutine, object self, params object[]/*!*/ args) {
if (startRoutine == null) {
throw RubyExceptions.CreateArgumentError("tried to create Proc object without a block");
}
RubyClass cls = self as RubyClass;
return StartThread(context, (cls != null && cls.IsRubyClass) ? cls : null, startRoutine, args);
}
internal sealed class ThreadStarter {
internal BlockParam StartRoutine;
internal object[] Args;
internal Thread Creator;
// a Ractor's main thread runs this instead of yielding StartRoutine, in a group of its own
internal Func