Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions ffi/ffi_context.nim
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ proc startContextThreads*[T](ctx: ptr FFIContext[T]): Result[void, string] =

proc initContextResources*[T](ctx: ptr FFIContext[T]): Result[void, string] =
## On failure, deferred cleanup closes partial state; caller releases the slot.
ctx.myLib = nil
ctx.myLibOwned = false
ctx.myLibRefd = false
ctx.lifecycle.store(CtxLifecycle.Active)
Expand Down
3 changes: 3 additions & 0 deletions ffi/ffi_thread.nim
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,9 @@ proc ffiThreadBody[T](ctx: ptr FFIContext[T]) {.thread.} =
defer:
onFFIThread = false
servedCtx = nil
# The fallback lib lives in this thread's `ffiRun` closure and dies with it.
if not ctx.myLibOwned:
ctx.myLib = nil
unregisterWaitedSignal(ctx.reqSignal)
# Free handle refs on the thread that allocated them (refc heap is thread-local).
ctx[].handles.releaseAll()
Expand Down
28 changes: 28 additions & 0 deletions tests/unit/test_ffi_context.nim
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,34 @@ suite "FFIContextPool":
check staticPool.destroyFFIContext(filler.pop()).isOk()
check staticPool.staticFFIContext().isOk()

test "a reclaimed static slot does not keep the dead thread's fallback lib":
var d: CallbackData
initCallbackData(d)
defer:
deinitCallbackData(d)

let staticCtx = staticPool.staticFFIContext().valueOr:
assert false, "staticFFIContext failed: " & $error
return
check sendRequestToFFIThread(
staticCtx, PingRequest.ffiNewReq(testCallback, addr d, "static".cstring)
)
.isOk()
waitCallback(d)
check d.retCode == RET_OK
check not staticCtx.myLib.isNil()

check staticPool.destroyStaticFFIContext().isOk()
check staticCtx.myLib.isNil()

let ctx = staticPool.createFFIContext().valueOr:
assert false, "createFFIContext(pool) failed: " & $error
return
defer:
check staticPool.destroyFFIContext(ctx).isOk()
check ctx == staticCtx
check ctx.myLib.isNil()

test "requests are processed via pool context":
var pool: FFIContextPool[TestLib]
var d: CallbackData
Expand Down
Loading