# Best practice for calling Julia functions via API

**URL:** <https://discourse.julialang.org/t/best-practice-for-calling-julia-functions-via-api/135086>\
**Category:** General Usage\
**Tags:** api, garbage-collection, c, gc\
**Created:** [January 15, 2026, 8:04pm UTC](https://discourse.julialang.org/t/best-practice-for-calling-julia-functions-via-api/135086 "2026-01-15T20:04:30Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Chrysoberyl](https://avatars.discourse-cdn.com/v4/letter/c/ed655f/32.png) [@Chrysoberyl](https://discourse.julialang.org/u/Chrysoberyl)\
**Post date:** [January 15, 2026, 8:04pm UTC](https://discourse.julialang.org/t/best-practice-for-calling-julia-functions-via-api/135086/1 "2026-01-15T20:04:30Z")

</div>

In my setup, a Julia function calls a C/Rust function `play(agent, environment)`, which spawns some threads, and call functions on `agent`. `agent` and `environment` are Julia objects.

Each of these foreign threads gets registered using `jl_adopt_thread`, `jl_gc_safe_enter`, and `jl_enter_threaded_region`.

During a call to `play`, the following functions get called in order:

1. `jl_gc_safe_enter`
2. (some computation)
3. `jl_gc_unsafe_enter`
4. (calls a function in `agent`)
5. `jl_gc_unsafe_leave`
6. (some computation)
7. `jl_gc_safe_leave`

Steps 2-6 execute on multiple threads.

According to earlier threads e.g. [GC problems with `jl_gc_unsafe_enter` with multithreaded embedding](https://discourse.julialang.org/t/gc-problems-with-jl-gc-unsafe-enter-with-multithreaded-embedding/104467), it seems like calling `jl_gc_unsafe_enter` while the GC is running leads to segmentation faults. For this reason, what is the best practice for entering a GC-unsafe region? Do I have to call `jl_safepoint_wait_gc` before `jl_gc_unsafe_enter`? This function is not exposed in `julia.h`.

Moreover, does `ReentrantLock` work for Julia code called in this context?
