The manpage for pthread_mutex_init that Lock on linux is based on, states that (section: Destroying Mutexes):
Implementations are required to allow an object to be destroyed and freed and potentially unmapped (for example, lines A and B) immediately after the object is unlocked (line C).
Unfortunately without the lock/unlock on a lock before destroying it, there are multiple TSanitizers errors, in the following program:
import channels, os, std/isolation
type
WorkRequest = ref object
id: int
var
chanIn: Chan[WorkRequest]
thread: Thread[Chan[WorkRequest]]
proc workThread(chanIn: Chan[WorkRequest]) {.thread.} =
echo "Started work thread"
var req: WorkRequest
chanIn.recv(req)
echo "Got work ", req.id
proc main =
chanIn = newChan[WorkRequest]()
createThread(thread, workThread, chanIn)
chanIn.send(isolate(WorkRequest(id: 1)))
sleep(100) # Give thread time to run
# joinThread(thread)
main()
proc `=destroy`*[T](c: Chan[T]) =
if c.d != nil:
# this `fetchSub` returns current val then subs
# so count == 0 means we're the last
if c.d.atomicCounter.fetchSub(1, moAcquireRelease) == 0:
acquire(c.d.lock)
release(c.d.lock)
freeChannel(c.d)
At this point I don't know if it would make any sense to just use the example code in the above manpage and reuse the lock for the ref count, like:Edit: bad idea
proc `=destroy`*[T](c: Chan[T]) =
if c.d != nil:
acquire(c.d.lock)
dec c.d.counter
if c.d.counter == 0:
release(c.d.lock)
freeChannel(c.d)
The manpage for pthread_mutex_init that Lock on linux is based on, states that (section: Destroying Mutexes):
Unfortunately without the lock/unlock on a lock before destroying it, there are multiple TSanitizers errors, in the following program:
Outputs 4 data-race warnings for the lock.
================== WARNING: ThreadSanitizer: data race (pid=2177) Write of size 8 at 0x723c00000000 by main thread: #0 freeIt can be circumvented by using:
At this point I don't know if it would make any sense to just use the example code in the above manpage and reuse the lock for the ref count, like:Edit: bad ideaThoughts?