Re: [scheme-reports-wg2] Threads and futures Marc Nieper-Wißkirchen 21 Mar 2022 06:28 UTC

Am Mo., 21. März 2022 um 05:49 Uhr schrieb Marc Feeley (via srfi-226
list) <xxxxxx@srfi.schemers.org>:
>
> The SRFI-18 thread-specific and thread-specific-set! procedures are a primitive way of attaching local storage to a thread.  It essentially gives you a single cell of local storage, but a larger data structure can be put in that cell to give more storage.  That mechanism is low-level but sufficient for the programmer to create his own higher level thread abstraction.
>
> Gambit offers another mechanism that is based on extensible records (i.e. the definition of record subtypes).  Threads are essentially records of type “thread”.  Subtypes of the thread type can be defined using
>
>      (define-type-of-thread foo
>        field1
>        field2
>        …)
>
> If t is a “foo” thread, then (foo-field1 t) and (foo-field1-set! t x) can be used to read and write field1 of that thread.  So these fields are a form of thread local storage.  Starting a thread is however more involved because the thread needs to be initialized before it is started:
>
>      (define t (make-foo 42 …))
>
>      (write (foo-field1 t)) ;; prints 42
>
>      (thread-init! t (lambda () (write (foo-field1 (current-thread))))
>
>      (thread-start! t) ;; will start the thread, and it will print 42
>
> This mechanism gives an O(1) access time for thread local storage, which is hard to beat.

Thank you for sharing this; I will think about whether and how it fits
into SRFI 226.

We have actually two use cases here: Thread-local cells that are known
at thread creation time and thread-local cells that are to be
dynamically allocated. The former would be created via `_Thread_local`
in C11, the latter with `tss_create`. Gambit's mechanism gives an
optimal solution for the first use case. The second way of creating
thread-local cells could be built on the first or could be an extra
mechanism to exploit some performance characteristics of the
underlying platform.