Logo von Matlab Set Up Worker State

Matlab Set Up Worker State

OrganisationBeliebt
matlab
matlab-set-up-worker-state

Set up worker environment and per-worker state for parallel pools. Use when code needs paths, environment variables, database connections, loaded libraries, or expensive objects available on workers before parfor/parfeval runs. Teaches parallel.pool.Constant, parfevalOnAll, and parpool name-value pairs. Also use when refactoring existing code that uses spmd for side-effect setup (an anti-pattern). Triggers: worker setup, pool constant, per-worker state, non-serializable, loadlibrary on workers, database connection parfor, addpath workers, spmd before parfor, worker environment, reduce parfor overhead, parfor setup, resource creation in parallel loop, cannot serialize error, undefined function or variable on workers error, load data per worker, reduce data transfer, parallelize setup, improve parallel code.

Übersicht

Herausgebermatlab
Repositorymatlab-agentic-toolkit
Skill-Namematlab-set-up-worker-state
Sterne
1.2K
Forks
138
Mitgelieferte Dateien
1
Links
  • Anweisungen in Markdown

    Eine SKILL.md-Datei, die das Modell bei Bedarf lädt. So werden nur dann Token verbraucht, wenn eine Anfrage tatsächlich dazu passt.

  • Funktioniert mit jedem LLM

    KI-Skills bestehen aus reinem Markdown, nicht aus anbieterspezifischem Code. Daher funktionieren sie mit GPT, Claude, Gemini, Grok oder einem lokalen Modell.

  • 1 mitgelieferte Dateien

    Skripte, Vorlagen und Referenzmaterial, die das Modell bei der Arbeit lesen kann. Die Dateien sind schreibgeschützt und werden niemals ausgeführt.

  • Open Source

    Von matlab auf GitHub veröffentlicht. Prüfen Sie den Quellinhalt vor der Installation.

Installation

Installieren Sie den KI-Skill Matlab Set Up Worker State in TypingMind, um ihn mit jedem LLM zu nutzen, oder fügen Sie ihn einem anderen Agenten hinzu, der SKILL.md lesen kann.

1

In TypingMind installieren

TypingMind installiert einen Skill direkt aus seinem GitHub-Ordner — liest SKILL.md, bündelt die Ressourcendateien und speichert das Ergebnis lokal.

  1. Öffnen Sie die App und gehen Sie zu Plugins → Skills.
  2. Wählen Sie „Von GitHub installieren“.
  3. Fügen Sie die unten angegebene URL des Skill-Ordners ein und bestätigen Sie.
    https://github.com/matlab/matlab-agentic-toolkit/tree/main/skills-catalog/parallel-computing/matlab-set-up-worker-state
  4. Aktivieren Sie den Skill in jedem Chat, in dem er verfügbar sein soll.
Plugins → Skills → Skill anlegen → Über GitHub-URL. Fügen Sie dann die Ordner-URL ein und klicken Sie auf „Weiter“.
2

In einem anderen Agenten installieren

Jeder Agent, der das Agent-Skills-Format lesen kann, kann diesen Skill nutzen — kopieren Sie den Ordner in das Skill-Verzeichnis des jeweiligen Agenten.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/matlab/matlab-agentic-toolkit.git /tmp/matlab-agentic-toolkit
mkdir -p .claude/skills
cp -r /tmp/matlab-agentic-toolkit/skills-catalog/parallel-computing/matlab-set-up-worker-state .claude/skills/matlab-set-up-worker-state
Starten Sie Claude Code nach dem Kopieren neu, damit der neue Skill erkannt wird.

In TypingMind verwenden

Aktivieren Sie Matlab Set Up Worker State in einem beliebigen Chat in TypingMind. Den Rest übernimmt das Modell. Name und Beschreibung des Skills stehen im System-Prompt. Sobald eine Anfrage passt, lädt das Modell selbstständig die vollständigen Anweisungen — Sie müssen den Skill nie manuell aufrufen, und er verbraucht erst Token, wenn er tatsächlich genutzt wird.

Das Modell lädt Matlab Set Up Worker State automatisch, sobald eine passende Anfrage gestellt wird.

Funktioniert mit jedem KI-Modell

KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher ist Matlab Set Up Worker State nicht an das Modell gebunden, für das der Skill geschrieben wurde. Installieren Sie ihn einmal in TypingMind und nutzen Sie ihn mit GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder einem selbst betriebenen lokalen Modell — alles mit Ihren eigenen API-Keys.

  • Wird nur bei Bedarf geladen

    Der System-Prompt enthält nur den Namen und die Beschreibung. Die Anweisungen werden bei der ersten passenden Anfrage geladen. Ein ungenutzter Skill verursacht daher keine Kosten.

  • Modell im laufenden Chat wechseln

    Da der Skill aus Anweisungen statt aus Code besteht, funktioniert er auch nach einem Modellwechsel — das nächste Modell liest dieselbe SKILL.md-Datei.

Skill-Anweisungen

Dies ist der Inhalt von SKILL.md, den das Modell lädt. Lesen Sie ihn vor der Installation — ein Skill besteht aus Anweisungen, denen Ihr Modell folgt.

Set Up Worker State for Parallel Pools

By default, process workers in a parallel pool inherit MATLAB path state from their controlling client, but they do not inherit loaded libraries, open connections, or expensive pre-computed objects. Code that relies on any of these needs explicit setup. This skill teaches the correct APIs for each scenario. Most patterns target process-based pools; thread pool applicability is noted where relevant.

When to Use

  • Code needs a non-serializable resource on workers (database connections, COM objects, loaded shared libraries, file handles)
  • Code needs expensive one-time setup per worker (large object construction, data loading) that should not repeat every parfor iteration
  • Code needs paths or environment variables set on workers
  • User has existing code using spmd for side-effect setup before parfor (anti-pattern — help them modernise)
  • User sees errors about objects not being serializable when passed to parfor

When NOT to Use

  • Data already in client memory used in a single parfor loop (MATLAB broadcasts it automatically — Constant adds complexity for no benefit in this case)
  • Choosing between process and thread pools (out of scope — this skill assumes a pool type is already chosen)

Decision Framework

ScenarioCorrect APIWhy
Non-serializable resource needing cleanup (connections, libraries)parallel.pool.Constant(@buildFcn, @cleanupFcn)Constructs on each worker; automatic cleanup on delete
Data from a file needed on workersparallel.pool.Constant(@() load(file).var)Default for file-based data. Each worker loads from disk; client never holds the dataset. Always prefer this when the source is a file.
Data already in client memory, used in multiple parfor loopsparallel.pool.Constant(data)Transfers once for pool lifetime; without Constant, broadcast re-sends for every parfor loop. Not needed for a single parfor — let MATLAB broadcast.
One-shot side effect, no return value neededparfevalOnAll(pool, @fcn, 0)Runs once on all workers; use fetchOutputs to surface errors
Paths needed on workers — parpool call is in your codeparpool(..., AdditionalPaths=paths)Cleanest option when you can modify the parpool call; client path entries are inherited automatically
Paths needed on workers — pool opened elsewhere (can't modify call)parfevalOnAll(pool, @addpath, 0, p)Never delete and recreate a pool just to add paths — use parfevalOnAll on the existing pool
Environment variables on workers — parpool call is in your codeparpool(..., EnvironmentVariables=vars)Forwards named env vars from client to workers at startup; set values with setenv on the client before this call
Environment variables on workers — pool opened elsewhere (can't modify call)parfevalOnAll(pool, @setenv, 0, k, v)Never delete and recreate a pool just to set env vars — use parfevalOnAll on the existing pool

Thread pool notes: parallel.pool.Constant and parfevalOnAll also work on thread pools. However, thread workers share the client's process, so path and environment variable changes on the client are visible to threads automatically — AdditionalPaths and EnvironmentVariables do not apply. To modify a thread worker's environment, alter the client environment before the parfor.

The spmd Anti-Pattern

This applies equally to process pools and thread pools — prefer parallel.pool.Constant over spmd for worker state setup regardless of pool type.

What it looks like

matlab
% ANTI-PATTERN: Do not do this
spmd
    loadlibrary("mylib", "mylib.h");
end
parfor i = 1:100
    result(i) = calllib("mylib", "compute", data(i));
end
spmd
    unloadlibrary("mylib");
end

Why it's fragile

  1. No cleanup guarantee — if the parfor errors, the second spmd never runs
  2. Makes the pool fragile to worker disconnection — once a pool has run an spmd block, a single worker losing connection tears down the entire pool. Pools that never use spmd continue operating with fewer workers if one disconnects (no replacement occurs — the pool simply shrinks).
  3. Composite variables cannot be used inside parfor — values created in spmd are Composite objects that require indexing on the client; they cannot be referenced directly from within a parfor body

How to modernise

Replace with parallel.pool.Constant:

matlab
C = parallel.pool.Constant( ...
    @() loadAndReturn(), ...
    @(~) unloadlibrary("mylib")); %#ok<NASGU> — kept alive for cleanup

result = zeros(1, 100);
parfor i = 1:100
    result(i) = calllib("mylib", "compute", data(i));
end

% Cleanup happens automatically when C goes out of scope

Or with parfevalOnAll for simple side effects:

matlab
f = parfevalOnAll(pool, @setupWorker, 0);
fetchOutputs(f);

result = zeros(1, 100);
parfor i = 1:100
    result(i) = doWork(data(i));
end
% No automatic cleanup

Prefer parallel.pool.Constant when cleanup is needed. Use parfevalOnAll only for operations where cleanup is not required.

Patterns

Pattern 1: Loading data from a file for use in parfor

Always use the build-function form when the source is a file. This avoids loading the data into client memory entirely — each worker loads directly from disk. This is critical for large files but is also the correct default for any file-based data because it scales without code changes as file size grows.

matlab
c = parallel.pool.Constant(@() load("costSurface.mat").costSurface);

results = zeros(1, 10000);
parfor i = 1:10000
    results(i) = processWithLookup(input(i), c.Value);
end

Each worker calls load() once. The client never holds the full dataset.

Do NOT do this — loading on the client then wrapping defeats the purpose:

matlab
% WRONG: loads entire file into client memory, then copies to each worker
data = load("costSurface.mat").costSurface;
c = parallel.pool.Constant(data);  % client already paid the memory cost

The only time parallel.pool.Constant(data) (without a build function) is appropriate is when the data is already in client memory and used across multiple parfor loops (avoids re-broadcasting each loop). For a single parfor loop, just let MATLAB broadcast — Constant adds no benefit.

Pattern 2: Shared library (non-serializable, needs cleanup)

matlab
c = parallel.pool.Constant( ...
    @() loadLibraryAndReturn("mylib", "mylib.h"), ...
    @unloadlibrary);

results = zeros(1, 100);
parfor i = 1:100
    results(i) = calllib(c.Value, "compute", data(i));
end
% Cleanup runs automatically when c goes out of scope

function libName = loadLibraryAndReturn(libName, headerFile)
    loadlibrary(libName, headerFile);
end

The build function returns the library name so that c.Value is naturally referenced in the parfor body — this triggers lazy initialisation. The cleanup function receives the same value and calls unloadlibrary on it.

Pattern 3: One-shot setup with parfevalOnAll (no cleanup needed)

matlab
pool = gcp;
f = parfevalOnAll(pool, @setupWorker, 0);
fetchOutputs(f);

Pattern 4: Database connection (use createConnectionForPool)

Database connections are a common specific case that requires Database Toolbox. Prefer the purpose-built helper createConnectionForPool over a hand-rolled parallel.pool.Constant. It returns a parallel.pool.Constant whose value is a per-worker connection to the configured data source, and it handles worker-side initialisation that a naive database() call inside a Constant build function does not.

matlab
pool = gcp;
c = createConnectionForPool(pool, "MyDataSource", "", "");

results = cell(1, 1000);
parfor i = 1:1000
    conn = c.Value;
    results{i} = fetch(conn, sprintf("SELECT val FROM t WHERE id=%d", i));
end

The returned Constant is the standard parallel.pool.Constant type, so it participates in the normal lifetime model: connections are torn down when the Constant goes out of scope or the pool shuts down.

Recognising When pool.Constant Is Needed

Look for these signals in user code:

SignalIndicates
Object created and destroyed every parfor iterationPer-worker resource needed
"Cannot serialize" or "not valid on workers" errorsNon-serializable resource
loadlibrary/unloadlibrary inside parforLibrary should persist across iterations
database()/close() inside parforConnection should persist
fopen/fclose inside parfor (same file)File handle should persist
Large variable used read-only in multiple parfor loops (>100 MB)Send-once with Constant
spmd block doing setup before parforModernise to Constant or parfevalOnAll

Common Mistakes

What the agent does wrongWhy it's wrongCorrect approach
Uses spmd before parfor for setupFragile, no cleanup, pool tears down if any worker disconnectsparallel.pool.Constant with build + cleanup functions
Creates resource every iterationMassive overhead (N connections for N iterations)parallel.pool.Constant — one per worker
Uses persistent variables on workersNo cleanup, hard to reason about lifecycleparallel.pool.Constant — explicit lifecycle
Tries to send non-serializable object from clientWill error — can't serialize connections, librariesUse build function form: parallel.pool.Constant(@buildFcn)
Build function calls a function not on the worker pathWorkers can't find it — "Unable to create parallel.pool.Constant on the workers"Ensure build function helpers are on the path (or use AdditionalPaths). Local functions in the same file work — MATLAB captures them with the handle.
Uses addpath inside parfor on process poolRuns every iteration unnecessarilyparpool(..., AdditionalPaths=...) or parfevalOnAll
Deletes and recreates pool to change paths or env varsExtremely expensive — pool startup can take 30+ seconds and may queue on a schedulerUse parfevalOnAll on the existing pool instead

Key Functions

FunctionProductAvailable FromPurpose
parallel.pool.ConstantParallel Computing ToolboxR2015bPer-worker state with lifecycle management
parfevalOnAllParallel Computing ToolboxR2013bRun a function once on all workers
parpool(..., AdditionalPaths=)Parallel Computing ToolboxR2025aSet worker paths at pool creation
parpool(..., EnvironmentVariables=)Parallel Computing ToolboxR2017bForward env vars to workers at pool creation
createConnectionForPoolDatabase ToolboxR2019aPer-worker database connections (optional)

Conventions

  • Prefer parallel.pool.Constant over spmd for any worker state that persists across parfor iterations
  • The build-function form (parallel.pool.Constant(@buildFcn)) is lazily initialised — the build function does not run until c.Value is first accessed on a worker. Always reference c.Value inside the parfor body to ensure initialisation occurs.
  • Always provide a cleanup function when the resource needs explicit teardown
  • Use parfevalOnAll only when no handle is needed back and no cleanup is required
  • Use parpool name-value pairs when the setup is needed for the entire pool lifetime (paths, env vars)
  • When modernising spmd-based setup code, preserve the original's intent (what resource, what cleanup) while switching to Constant

Copyright 2026 The MathWorks, Inc.


Mitgelieferte Dateien

Das Modell liest diese Dateien bei Bedarf, während der Skill geladen ist. Sie werden als lesbare Dateien bereitgestellt und niemals ausgeführt.

Häufig gestellte Fragen

Was macht der KI-Skill Matlab Set Up Worker State?

Set up worker environment and per-worker state for parallel pools. Use when code needs paths, environment variables, database connections, loaded libraries, or expensive objects available on workers before parfor/parfeval runs. Teaches parallel.pool.Constant, parfevalOnAll, and parpool name-value pairs. Also use when refactoring existing code that uses spmd for side-effect setup (an anti-pattern). Triggers: worker setup, pool constant, per-worker state, non-serializable, loadlibrary on workers, database connection parfor, addpath workers, spmd before parfor, worker environment, reduce parfo...

Warum Matlab Set Up Worker State in TypingMind nutzen?

Weil Sie den Skill einmal installieren und mit jedem Modell verwenden können. Matlab Set Up Worker State besteht aus reinem Markdown statt aus anbieterspezifischem Code. So funktioniert derselbe Skill mit GPT-5, Claude, Gemini, Grok oder einem lokalen Modell – und Sie können das Modell mitten im Chat wechseln, ohne dass der Skill seine Funktion verliert. TypingMind verwendet Ihre eigenen API-Schlüssel. Sie bezahlen die Anbieter daher direkt statt über ein Abonnement pro Nutzerplatz, und Ihre Skills und Chats bleiben in Ihrem eigenen Speicher.

Wie installiere ich Matlab Set Up Worker State in TypingMind?

Öffnen Sie in TypingMind Plugins → Skills → Von GitHub installieren und fügen Sie https://github.com/matlab/matlab-agentic-toolkit/tree/main/skills-catalog/parallel-computing/matlab-set-up-worker-state ein. TypingMind liest die Datei SKILL.md, bündelt die zugehörigen Dateien und installiert alles als Skill, den Sie für jeden Chat einzeln aktivieren können.

Welche KI-Modelle können Matlab Set Up Worker State nutzen?

Jedes Modell, das Sie in TypingMind verbinden. KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher können GPT, Claude, Gemini, Grok und lokale Modelle diesen Skill laden, wenn eine Anfrage dazu passt.

Wie viele KI-Modelle kann ich mit Matlab Set Up Worker State verwenden?

So viele Sie möchten. Solange ein Modell Skills unterstützt, können Sie Matlab Set Up Worker State damit verwenden – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama und weitere – alles in TypingMind mit Ihren eigenen API-Schlüsseln.

Ist der KI-Skill Matlab Set Up Worker State kostenlos?

Der Skill wird von matlab auf GitHub veröffentlicht. Die Lizenzbedingungen finden Sie im Repository. Sie bezahlen nur Ihren eigenen KI-Anbieter für die verwendeten Token.

Was sind KI-Skills?

Ein KI-Skill ist ein wiederverwendbares Anweisungspaket, das einem KI-Modell vermittelt, wie es eine bestimmte Aufgabe erledigt. Es folgt dem offenen Format Agent Skills: eine Datei namens SKILL.md mit einem Namen und einer Beschreibung sowie allen Skripten, Vorlagen oder Referenzdateien, die das Modell möglicherweise benötigt. Das Modell liest die Anweisungen nur, wenn Ihre Anfrage zum Skill passt. Ein installierter Skill verursacht daher erst Kosten, wenn er verwendet wird.

Wie unterscheiden sich KI-Skills von Plugins oder MCP-Servern?

Ein Plugin oder MCP-Server stellt einem Modell neue aufrufbare Tools bereit – Code, der auf einem System ausgeführt wird und ein Ergebnis zurückgibt. Ein KI-Skill vermittelt dem Modell stattdessen Wissen und Vorgehensweisen: wie es eine Aufgabe angeht, welche Schritte es befolgt und wie eine gute Ausgabe aussieht. Skills bestehen aus reinem Markdown und benötigen daher weder Server noch API-Schlüssel oder Laufzeitumgebung. Sie funktionieren mit jedem Modell.

Alle

Jetzt eigenen KI-Arbeitsbereich einrichten

Abonnieren Sie unseren Newsletter und erfahren Sie mehr über neue Funktionen und kommende Gewinnspiele 👇