Sync: Difference between revisions

From MemCP
Jump to navigation Jump to search
No edit summary
(Refresh MemCP documentation: accuracy, operational guidance, performance profile and maintained API reference)
 
Line 1: Line 1:
<!-- Copyright (C) 2026 Carl-Philip Haensch -->
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->
<span id="sync"></span>
= Sync =
= Sync =


The '''Sync''' module provides synchronization and concurrency functionality for the SCM programming language. This module includes:
<!-- Generated from MemCP c42e19eba on 2026-08-27; do not edit manually. -->
<div class="mw-message-box mw-message-box-notice">Generated from MemCP commit <code>c42e19eba</code> on 27 August 2026. See [[Full SCM API documentation]].</div>


* '''Session management''': Functions to create threadsafe key-value stores (newsession)
The '''Sync''' module provides explicit coordination for state that must cross functional scopes or concurrent tasks. It includes:
* '''Context handling''': Context management with session support (context)
* '''Timing control''': Functions to pause execution (sleep)
* '''Function caching''': One-time execution wrappers with result caching (once)
* '''Thread synchronization''': Mutex creation for serialized access (mutex)


These functions provide essential tools for managing concurrent operations, shared state, and synchronization in multi-threaded SCM programs.
* thread-safe sessions and contextual values;
* promises and one-time publication;
* mutex and serialized execution helpers;
* shared computation and cache maps;
* timing, waiting, and lifecycle coordination.


← Back to [[Full SCM API documentation]]
Prefer ordinary immutable values when no sharing is required. Use these primitives to make ownership, failure, and publication explicit rather than relying on outer-scope mutation, which this Scheme dialect does not provide.


== newpromise ==
== newpromise ==


Creates a single-value promise cell (thread-safe via CAS spin-lock). Returns a tagPromise Scmer. (newpromise) allocates a [2]Scmer backing; (newpromise list) reuses an existing ≥2-element slice as backing with zero extra allocation. API: (p &quot;value&quot;) reads current value (nil if pending), (p &quot;value&quot; v) resolves, (p &quot;once&quot; v) resolves once (panics if already fulfilled/failed), (p &quot;once&quot; v msg) resolves once with custom panic message, (p &quot;state&quot;) returns state (nil/true/false), (p &quot;fail&quot;) sets failed and clears the stored value, (p &quot;fail&quot; err) sets failed and stores err as payload.
Creates a thread-safe promise that lets parallel work publish one result for other code to inspect. Use it for shared initialization, asynchronous results, or ensuring that only the first successful producer resolves a value. Read with (promise &quot;value&quot;), inspect completion with (promise &quot;state&quot;), resolve with (promise &quot;value&quot; value), resolve exactly once with (promise &quot;once&quot; value), and mark failure with (promise &quot;fail&quot; error).


'''Allowed number of parameters:''' 0–1
'''Allowed number of parameters:''' 0–1
Line 22: Line 27:
=== Parameters ===
=== Parameters ===


* '''list''' (<code>any</code>): optional: ≥2-element slice to use as backing ''(optional)''
* '''storage''' (<code>list&lt;any&gt;</code>): optional existing two-item list used to hold the promise state; most callers omit this ''(optional)''
** '''slot''' (<code>any</code>): promise state or value slot


<span id="returns"></span>
<span id="returns"></span>
=== Returns ===
=== Returns ===


<code>func(operation:string, value:any?, msg:string?) -&gt; any</code>
* '''promise''' (<code>func</code>): operation-based accessor for reading, resolving, or failing the promise
** '''Parameters'''
*** '''operation''' (<code>string</code>): one of: value, state, fail, once
*** '''value''' (<code>any</code>): value to store (for value/once/fail) ''(optional)''
*** '''message''' (<code>string</code>): optional error message used when once finds an already completed promise ''(optional)''
** '''Returns'''
*** '''result''' (<code>any</code>): stored value, state flag, or operation result


== newsession ==
== newsession ==


Creates a new session which is a threadsafe key-value store. Besides get/set/list, get_or_compute_scoped shares concurrent computation by a query-local handle.
Creates a thread-safe key-value session. Call it without arguments to list values, with a key to read, with a key and value to store, or with get_or_compute_scoped, a scope, a key, and a producer to share one concurrent computation.


'''Allowed number of parameters:''' 0–0
'''Allowed number of parameters:''' 0–0
Line 43: Line 55:
=== Returns ===
=== Returns ===


<code>func(key_or_operation:any?, value_scope_or_key:any?, key_or_producer:any?, scoped_producer:func?) -&gt; any</code>
* '''session''' (<code>func</code>): session accessor accepting exactly zero, one, two, or four arguments
** '''Parameters'''
*** '''key_or_operation''' (<code>any</code>): key, or get_or_compute_scoped ''(optional)''
*** '''value_or_scope''' (<code>any</code>): value to store, or scope for get_or_compute_scoped ''(optional)''
*** '''scoped_key''' (<code>any</code>): cache key used by get_or_compute_scoped ''(optional)''
*** '''scoped_producer''' (<code>func</code>): producer used only by the four-argument get_or_compute_scoped form ''(optional)''
**** '''Returns'''
***** '''value''' (<code>any</code>): computed value cached for the scope and key
** '''Returns'''
*** '''result''' (<code>any</code>): value list, stored value, retrieved value, or shared computed value


== with_session ==
== with_session ==
Line 54: Line 75:
=== Parameters ===
=== Parameters ===


* '''session''' (<code>func(key:any?, value:any?) -&gt; any</code>): the session to install
* '''session''' (<code>func</code>): the session to install
** '''Parameters'''
*** '''key''' (<code>any</code>) ''(optional)''
*** '''value''' (<code>any</code>) ''(optional)''
** '''Returns'''
*** '''value''' (<code>any</code>)
* '''fn''' (<code>func</code>): the function to execute
* '''fn''' (<code>func</code>): the function to execute
** '''Returns'''
*** '''value''' (<code>any</code>)


<span id="returns-2"></span>
<span id="returns-2"></span>
=== Returns ===
=== Returns ===


<code>any</code>
* '''value''' (<code>any</code>)


== context ==
== context ==
Line 76: Line 104:
=== Returns ===
=== Returns ===


<code>any</code>
* '''value''' (<code>any</code>)


== sleep ==
== sleep ==
Line 92: Line 120:
=== Returns ===
=== Returns ===


<code>bool</code>
* '''value''' (<code>bool</code>)


== once ==
== once ==
Line 104: Line 132:


* '''f''' (<code>func</code>): function that produces the result value
* '''f''' (<code>func</code>): function that produces the result value
** '''Parameters'''
*** '''argument''' (<code>any</code>) ''(variadic)''
** '''Returns'''
*** '''result''' (<code>any</code>)


<span id="returns-5"></span>
<span id="returns-5"></span>
=== Returns ===
=== Returns ===


<code>func(args:any...) -&gt; any</code>
* '''once_wrapper''' (<code>func</code>): calls the wrapped function once and returns its cached result thereafter
** '''Parameters'''
*** '''args''' (<code>any</code>): arguments forwarded to the wrapped function on first call ''(variadic)''
** '''Returns'''
*** '''result''' (<code>any</code>): result cached from the first call


== mutex ==
== mutex ==
Line 124: Line 160:
=== Returns ===
=== Returns ===


<code>func(fn:func) -&gt; any</code>
* '''locked''' (<code>func</code>): executes one parameterless function while holding the mutex
** '''Parameters'''
*** '''fn''' (<code>func</code>): parameterless function to execute under the lock
**** '''Returns'''
***** '''result''' (<code>any</code>)
** '''Returns'''
*** '''result''' (<code>any</code>): result returned by the protected function


== numcpu ==
== numcpu ==
Line 140: Line 182:
=== Returns ===
=== Returns ===


<code>number</code>
* '''value''' (<code>number</code>)


== memstats ==
== memstats ==
Line 156: Line 198:
=== Returns ===
=== Returns ===


<code>dict</code>
* '''value''' (<code>dict</code>)


<span id="settimeout"></span>
<span id="settimeout"></span>
Line 168: Line 210:
=== Parameters ===
=== Parameters ===


* '''callback''' (<code>func(args:any...) -&gt; any</code>): function to execute once the timeout expires
* '''callback''' (<code>func</code>): function to execute once the timeout expires
** '''Parameters'''
*** '''args''' (<code>any</code>) ''(variadic)''
** '''Returns'''
*** '''value''' (<code>any</code>)
* '''milliseconds''' (<code>number</code>): milliseconds until execution
* '''milliseconds''' (<code>number</code>): milliseconds until execution
* '''args...''' (<code>any</code>): optional arguments forwarded to the callback ''(variadic)''
* '''args...''' (<code>any</code>): optional arguments forwarded to the callback ''(variadic)''
Line 175: Line 221:
=== Returns ===
=== Returns ===


<code>int</code>
* '''value''' (<code>int</code>)


<span id="cleartimeout"></span>
<span id="cleartimeout"></span>
Line 192: Line 238:
=== Returns ===
=== Returns ===


<code>bool</code>
* '''value''' (<code>bool</code>)

Latest revision as of 11:59, 28 August 2026


Sync

Generated from MemCP commit c42e19eba on 27 August 2026. See Full SCM API documentation.

The Sync module provides explicit coordination for state that must cross functional scopes or concurrent tasks. It includes:

  • thread-safe sessions and contextual values;
  • promises and one-time publication;
  • mutex and serialized execution helpers;
  • shared computation and cache maps;
  • timing, waiting, and lifecycle coordination.

Prefer ordinary immutable values when no sharing is required. Use these primitives to make ownership, failure, and publication explicit rather than relying on outer-scope mutation, which this Scheme dialect does not provide.

newpromise

Creates a thread-safe promise that lets parallel work publish one result for other code to inspect. Use it for shared initialization, asynchronous results, or ensuring that only the first successful producer resolves a value. Read with (promise "value"), inspect completion with (promise "state"), resolve with (promise "value" value), resolve exactly once with (promise "once" value), and mark failure with (promise "fail" error).

Allowed number of parameters: 0–1

Parameters

  • storage (list<any>): optional existing two-item list used to hold the promise state; most callers omit this (optional)
    • slot (any): promise state or value slot

Returns

  • promise (func): operation-based accessor for reading, resolving, or failing the promise
    • Parameters
      • operation (string): one of: value, state, fail, once
      • value (any): value to store (for value/once/fail) (optional)
      • message (string): optional error message used when once finds an already completed promise (optional)
    • Returns
      • result (any): stored value, state flag, or operation result

newsession

Creates a thread-safe key-value session. Call it without arguments to list values, with a key to read, with a key and value to store, or with get_or_compute_scoped, a scope, a key, and a producer to share one concurrent computation.

Allowed number of parameters: 0–0

Parameters

This function has no parameters.

Returns

  • session (func): session accessor accepting exactly zero, one, two, or four arguments
    • Parameters
      • key_or_operation (any): key, or get_or_compute_scoped (optional)
      • value_or_scope (any): value to store, or scope for get_or_compute_scoped (optional)
      • scoped_key (any): cache key used by get_or_compute_scoped (optional)
      • scoped_producer (func): producer used only by the four-argument get_or_compute_scoped form (optional)
        • Returns
          • value (any): computed value cached for the scope and key
    • Returns
      • result (any): value list, stored value, retrieved value, or shared computed value

with_session

Executes a function with the given session installed in the execution context, so storage operations can access the session's transaction state.

Allowed number of parameters: 2–2

Parameters

  • session (func): the session to install
    • Parameters
      • key (any) (optional)
      • value (any) (optional)
    • Returns
      • value (any)
  • fn (func): the function to execute
    • Returns
      • value (any)

Returns

  • value (any)

context

Context helper function. Each context also contains a session. (context func args) creates a new context and runs func in that context, (context "session") reads the session variable, (context "check") will check the liveliness of the context and otherwise throw an error

Allowed number of parameters: 0–10000

Parameters

  • args... (any): depends on the usage (variadic)

Returns

  • value (any)

sleep

sleeps the amount of seconds

Allowed number of parameters: 1–1

Parameters

  • duration (number): number of seconds to sleep

Returns

  • value (bool)

once

Creates a function wrapper that you can call multiple times but only gets executed once. The result value is cached and returned on a second call. You can add parameters to that resulting function that will be passed to the first run of the wrapped function.

Allowed number of parameters: 1–1

Parameters

  • f (func): function that produces the result value
    • Parameters
      • argument (any) (variadic)
    • Returns
      • result (any)

Returns

  • once_wrapper (func): calls the wrapped function once and returns its cached result thereafter
    • Parameters
      • args (any): arguments forwarded to the wrapped function on first call (variadic)
    • Returns
      • result (any): result cached from the first call

mutex

Creates a context-aware mutex. The return value serializes calls to parameterless functions and stops waiting when the current request is cancelled.

Allowed number of parameters: 0–0

Parameters

This function has no parameters.

Returns

  • locked (func): executes one parameterless function while holding the mutex
    • Parameters
      • fn (func): parameterless function to execute under the lock
        • Returns
          • result (any)
    • Returns
      • result (any): result returned by the protected function

numcpu

Returns the number of logical CPUs available for parallel execution

Allowed number of parameters: 0–0

Parameters

This function has no parameters.

Returns

  • value (number)

memstats

Returns memory statistics as a dict with keys: alloc, total_alloc, sys, heap_alloc, heap_sys (all in bytes)

Allowed number of parameters: 0–0

Parameters

This function has no parameters.

Returns

  • value (dict)

setTimeout

Schedules a callback to run after the given delay in milliseconds (fractional values allowed for sub-millisecond precision).

Allowed number of parameters: 2–10000

Parameters

  • callback (func): function to execute once the timeout expires
    • Parameters
      • args (any) (variadic)
    • Returns
      • value (any)
  • milliseconds (number): milliseconds until execution
  • args... (any): optional arguments forwarded to the callback (variadic)

Returns

  • value (int)

clearTimeout

Cancels a timeout created with setTimeout.

Allowed number of parameters: 1–1

Parameters

  • id (number): identifier returned by setTimeout

Returns

  • value (bool)