Skip to content

Commit

Permalink
adding lock
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielmer committed Feb 3, 2025
1 parent e923df3 commit 6c305fb
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion library/waku_thread/waku_thread.nim
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@
{.pragma: callback, cdecl, raises: [], gcsafe.}
{.passc: "-fPIC".}

import std/[options, atomics, os, net]
import std/[options, atomics, os, net, locks]
import chronicles, chronos, chronos/threadsync, taskpools/channels_spsc_single, results
import waku/factory/waku, ./inter_thread_communication/waku_thread_request, ../ffi_types

type WakuContext* = object
thread: Thread[(ptr WakuContext)]
lock: Lock
reqChannel: ChannelSPSCSingle[ptr WakuThreadRequest]
reqSignal: ThreadSignalPtr
# to inform The Waku Thread (a.k.a TWT) that a new request is sent
Expand Down Expand Up @@ -59,6 +60,7 @@ proc createWakuThread*(): Result[ptr WakuContext, string] =
return err("couldn't create reqSignal ThreadSignalPtr")
ctx.reqReceivedSignal = ThreadSignalPtr.new().valueOr:
return err("couldn't create reqReceivedSignal ThreadSignalPtr")
ctx.lock.initLock()

ctx.running.store(true)

Expand All @@ -81,6 +83,7 @@ proc destroyWakuThread*(ctx: ptr WakuContext): Result[void, string] =
return err("failed to signal reqSignal on time in destroyWakuThread")

joinThread(ctx.thread)
ctx.lock.deinitLock()
?ctx.reqSignal.close()
?ctx.reqReceivedSignal.close()
freeShared(ctx)
Expand All @@ -96,6 +99,7 @@ proc sendRequestToWakuThread*(
): Result[void, string] =
let req = WakuThreadRequest.createShared(reqType, reqContent, callback, userData)
## Sending the request
ctx.lock.acquire()
let sentOk = ctx.reqChannel.trySend(req)
if not sentOk:
deallocShared(req)
Expand All @@ -112,6 +116,8 @@ proc sendRequestToWakuThread*(

## wait until the Waku Thread properly received the request
let res = ctx.reqReceivedSignal.waitSync()
ctx.lock.release()

if res.isErr():
deallocShared(req)
return err("Couldn't receive reqReceivedSignal signal")
Expand Down

0 comments on commit 6c305fb

Please sign in to comment.