How to use idfkit from several threads¶
This guide shows you how to load, check, change and write models on a thread pool without corrupting them, and how to get real parallelism from it. It assumes you already have the work split into jobs, one model or one variant each.
Everything here is Python. The TypeScript library has no shared-memory threads; its equivalent, parsing off the main thread, hands a worker its own copy of the text.
Requires idfkit 1.3.0 or later
The rules below hold from idfkit 1.3.0, which loads each schema version once under a lock and makes its process-wide caches safe on a free-threaded build.
Choose the kind of concurrency the job needs¶
Threads are one of four options, and often not the right one. Find the row that matches your job before writing a thread pool.
| The job | Use | Why |
|---|---|---|
| Run many EnergyPlus simulations on one machine | simulate_batch (a thread pool) |
The work happens in EnergyPlus subprocesses, so threads run them in parallel on any build of Python, and all of them share one simulation cache. |
| Run simulations from an async web server, or alongside other network calls | async_simulate_batch |
It never blocks the event loop, and streams results as they finish. |
| Serve many requests from one base model (a web API, a desktop app) | Threads sharing a read-only base model, one copy per request | Loading once and copying per request is far cheaper than loading per request. See the web-service example. |
| Load, validate, transform or write many models, CPU-bound, on a free-threaded build | A thread pool | Threads run in parallel without pickling models between processes. |
| The same CPU-bound work on a regular build | A process pool | The GIL lets only one thread run Python at a time, so threads would not be faster. |
| Download weather files or geocode addresses | A pool over distinct stations; geocoding on one thread | Downloads are network-bound, so threads help on any build. Geocoding is rate-limited to one request a second, so threads do not speed it up. |
| Thousands of simulations, or more than one machine | A task queue or a distributed runner | One machine's cores are the limit. See campaigns beyond one machine. |
1. Decide what each thread may touch¶
Look up what your threads share in this table before writing any code. Everything not listed is a document, and the last column is what to do with it.
| Threads share | Safe? | What to do |
|---|---|---|
| Nothing but the schema: one document per thread | Yes | Nothing: separate documents are independent. |
| One document that no thread changes | Yes | Nothing, as long as it stays unchanged for as long as the threads read it. |
| One document that some thread changes | No | Give each thread a doc.copy(), or guard every access with one lock. |
| A batch of simulation jobs | Yes | Leave each job's model unedited until the batch returns. |
| One weather cache directory | Yes | Do not call clear_cache() while others use it. Download each station once first to save bandwidth across processes (step 4). |
Reading includes writing a file (write_idf, write_epjson), validating, copying, following
references (get_referencing), attribute reads, and evaluating schedules. Changing includes
add, removeidfobject, rename, and assigning to any field.
A document changed by two threads at once does not fail reliably. Sometimes a reader raises
RuntimeError: dictionary changed size during iteration, or the reference graph raises
KeyError. As often, nothing raises and the model is simply wrong: an object missing, a
reference left dangling. Do not treat the absence of an exception as evidence that the sharing
was safe.
2. Give each thread its own document¶
When the jobs are independent models, load them on the pool. This is the case that parallelises best.
from concurrent.futures import ThreadPoolExecutor
from idfkit import load_idf, validate_document
with ThreadPoolExecutor() as pool:
docs = list(pool.map(load_idf, paths))
results = list(pool.map(validate_document, docs))
When the threads only read one model, share it as is:
from concurrent.futures import ThreadPoolExecutor
from idfkit import write_idf
def render(_: int) -> str:
return write_idf(doc) or ""
# Safe only while no thread changes `doc`.
with ThreadPoolExecutor() as pool:
texts = list(pool.map(render, range(8)))
3. Copy a shared model before changing it¶
When each thread needs a variant of one base model, give each thread a copy and change only
that copy. doc.copy() is a read, so many threads may copy the same base model at once.
from concurrent.futures import ThreadPoolExecutor
def make_variant(thickness: float) -> IDFDocument:
variant = doc.copy() # a private copy: this thread may change it freely
variant["Material"]["Insulation"].thickness = thickness
return variant
with ThreadPoolExecutor() as pool:
variants = list(pool.map(make_variant, [0.05, 0.10, 0.15]))
If the threads must change one document together, put every access behind one lock you own, the reads included: a thread that reads while another writes is as unsafe as two writers.
import threading
from concurrent.futures import ThreadPoolExecutor
doc_lock = threading.Lock()
def add_zone(name: str) -> None:
with doc_lock: # every read and every write of `doc`, not only the writes
doc.add("Zone", name)
with ThreadPoolExecutor() as pool:
list(pool.map(add_zone, ["North", "South", "East", "West"]))
4. Fetch weather files once, before fanning out¶
Threads and processes can share one weather cache directory, station index included. Every file in it is written under a temporary name and renamed into place, so a concurrent caller sees either nothing or the complete file. Threads of one process download a station once, but separate processes that miss the same station at the same moment each download it. When many jobs in several processes share a few stations, download each station once and hand the paths to the pool:
from concurrent.futures import ThreadPoolExecutor
from idfkit.weather import WeatherDownloader
downloader = WeatherDownloader()
# Download each station once, before the parallel part starts: safe to skip, but it saves bandwidth.
files = {station.wmo: downloader.download(station) for station in stations}
with ThreadPoolExecutor() as pool:
epw_paths = list(pool.map(lambda station: files[station.wmo].epw, stations))
simulate_batch and async_simulate_batch need no extra care: each job copies its model when it
starts, and the simulation cache commits each entry with an atomic rename. A job that has not
started yet copies whatever its model holds by then, so do not edit a job's model until the
batch returns.
5. Run on a free-threaded build for parallel speed¶
On a regular build of CPython, the global interpreter lock (GIL) lets one thread run Python at a time, so CPU-bound idfkit work on a pool runs no faster than on one thread. The steps above keep it correct there; they do not make it faster.
To run threads in parallel, use the free-threaded build of Python 3.14:
Check that the GIL is really off in the environment your code runs in:
import sys
import sysconfig
free_threaded = bool(sysconfig.get_config_var("Py_GIL_DISABLED"))
gil_enabled = getattr(sys, "_is_gil_enabled", lambda: True)()
print(f"free-threaded build: {free_threaded}, GIL enabled: {gil_enabled}")
If GIL enabled prints True on a free-threaded build, an extension module re-enabled it at
import and the interpreter printed a RuntimeWarning naming it. idfkit itself never does. Of
its optional extras, only pandas before 3.0 does; upgrade to pandas>=3.0, or set
PYTHON_GIL=0 to force the GIL off at your own risk.
For CPU-bound batch work on a regular build, use processes instead. A document pickles cheaply, because its schema travels by version rather than by content:
from concurrent.futures import ProcessPoolExecutor
from idfkit import load_idf
if __name__ == "__main__": # required: spawn and forkserver workers re-import this module
with ProcessPoolExecutor() as pool:
docs = list(pool.map(load_idf, paths))
Worked examples¶
A web service that shares one base model¶
A web server calls its handlers on a pool of threads, several at once. Load the base model once at start-up and never change it afterwards; every request works on its own copy.
from idfkit import IDFDocument, load_idf, write_idf
# Loaded once at start-up, then only ever read: every request thread may share it.
BASE = load_idf("office.idf")
def handle_request(insulation_m: float) -> str:
"""Called on whatever thread the web server picks, possibly many at once."""
model: IDFDocument = BASE.copy() # this request's private model
model["Material"]["Insulation"].thickness = insulation_m
return write_idf(model) or ""
Two things keep this safe. Nothing writes to BASE after start-up, so the copies taken by
concurrent requests are all copies of the same, unchanging model. And each request's changes
land on its own copy, which no other thread can see. If the base model must change while the
server runs, load the new version into a fresh document and swap the global name in one
assignment, rather than editing the shared one in place.
A parametric campaign on one machine¶
A parametric study builds variants, simulates them, and reads the results back: three stages with different concurrency needs.
from concurrent.futures import ThreadPoolExecutor
from idfkit.simulation import SimulationCache, SimulationJob, SimulationResult, simulate_batch
THICKNESSES = [0.05, 0.10, 0.15, 0.20]
def make_variant(thickness: float) -> IDFDocument:
variant = base.copy() # never change `base` itself: other threads are copying it
variant["Material"]["Insulation"].thickness = thickness
return variant
# 1. Build the variants. CPU-bound Python: parallel on a free-threaded build only.
with ThreadPoolExecutor() as pool:
variants = list(pool.map(make_variant, THICKNESSES))
# 2. Simulate. EnergyPlus runs as a subprocess, so threads are enough on any build.
# Do not touch `variants` again until the batch returns.
jobs = [
SimulationJob(model=v, weather="site.epw", label=f"ins-{t}", annual=True) for v, t in zip(variants, THICKNESSES)
]
batch = simulate_batch(jobs, max_workers=4, cache=SimulationCache())
# 3. Read the results. Each worker opens, queries and closes its own result's SQL output:
# the SQLite connection belongs to the thread that opened it.
def site_energy(result: SimulationResult) -> str:
try:
return result.sql.get_tabular_value(
"AnnualBuildingUtilityPerformanceSummary", "Site and Source Energy", "Total Site Energy", "Total Energy"
)
finally:
result.close()
with ThreadPoolExecutor() as pool:
totals = list(pool.map(site_energy, batch.succeeded))
- Variants are built on a thread pool from one shared base, each thread working on its own copy. On a regular build this stage gains nothing from threads, but it is safe; on a free-threaded build it runs in parallel.
- Simulations run through
simulate_batch, whose threads spend their time waiting on EnergyPlus. Raisemax_workersuntil the machine's cores are busy, not beyond: each worker holds one EnergyPlus process and its working directory. The sharedSimulationCacheskips any variant already run, in this process or another. - Results are read by whichever thread will use them. A result opens its SQLite output on first access, and that connection belongs to the thread that opened it, so read, query and close a result on one thread.
Campaigns beyond one machine¶
A campaign of thousands of simulations outgrows one machine's cores long before it outgrows
simulate_batch. Move the parallelism up a level: a queue hands each job to a worker process
on some machine, and each worker loads its own model and usually runs one simulation at a time. Nothing
is shared between workers but files, which is exactly the situation idfkit's process-safe
simulation cache is built for.
- How to run simulations as Celery tasks: a task queue in front of a pool of workers.
- How to run distributed simulations with Scythe: experiments defined as functions and fanned out over a cluster.
- How to store simulation results in S3: a shared result store for workers that share no disk.
Inside each worker the rules on this page still hold. A worker that runs several simulations at
once is running simulate_batch, and a worker that also builds variants follows step 3.
Verify¶
Run the work twice, once on one thread and once on the pool, and compare the outputs: written files, validation results, or simulation results should be identical. On a free-threaded build, also compare the wall time; if four threads are no faster than one, check that the GIL is off (step 5).
Related¶
- Why idfkit locks its caches and not your documents: why the rules are what they are, and how far threads scale.
- How to run batch simulations: parallel EnergyPlus runs.
- Caching strategy: which caches are shared between processes.