Skip to content

Commit

Permalink
#55 Refactor access to atomicCounter
Browse files Browse the repository at this point in the history
Tail and head are atomics and received getter/setter procs for better readability.

For consistency, this was now also done for the atomicCounter field.
  • Loading branch information
PhilippMDoerner committed Jan 9, 2024
1 parent 9e30e72 commit 5eb9684
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions threading/channels.nim
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,12 @@ proc setTail(chan: ChannelRaw, value: int, order: MemoryOrder = moRelaxed) {.inl
proc setHead(chan: ChannelRaw, value: int, order: MemoryOrder = moRelaxed) {.inline.} =
chan.head.store(value, order)

func getAtomicCounter(chan: ChannelRaw, order: MemoryOrder = moRelaxed): int {.inline.} =
chan.atomicCounter.load(order)

proc setAtomicCounter(chan: ChannelRaw, value: int, order: MemoryOrder = moRelaxed) {.inline.} =
chan.atomicCounter.store(value, order)

func numItems(chan: ChannelRaw): int {.inline.} =
result = chan.getHead() - chan.getTail()
if result < 0:
Expand Down Expand Up @@ -159,7 +165,7 @@ proc allocChannel(size, n: int): ChannelRaw =
result.slots = n
result.setHead(0)
result.setTail(0)
result.atomicCounter.store(0, moRelaxed)
result.setAtomicCounter(0)


proc freeChannel(chan: ChannelRaw) =
Expand Down Expand Up @@ -258,15 +264,15 @@ type
when defined(nimAllowNonVarDestructor):
proc `=destroy`*[T](c: Chan[T]) =
if c.d != nil:
if load(c.d.atomicCounter, moAcquire) == 0:
if c.d.getAtomicCounter(moAcquire) == 0:
if c.d.buffer != nil:
freeChannel(c.d)
else:
atomicDec(c.d.atomicCounter)
else:
proc `=destroy`*[T](c: var Chan[T]) =
if c.d != nil:
if load(c.d.atomicCounter, moAcquire) == 0:
if c.d.getAtomicCounter(moAcquire) == 0:
if c.d.buffer != nil:
freeChannel(c.d)
else:
Expand Down

0 comments on commit 5eb9684

Please sign in to comment.