add helpers

This commit is contained in:
Jaremy Creechley 2023-08-24 15:25:15 -07:00 committed by Dmitriy Ryajov
parent 542fdf268c
commit e81c5faf40
No known key found for this signature in database
GPG Key ID: DA8C680CE7C657A4
2 changed files with 11 additions and 4 deletions

View File

@ -54,9 +54,15 @@ proc `=copy`*(a: var DataBuffer; b: DataBuffer) =
proc incrAtomicCount*(a: DataBuffer) =
let res = atomicAddFetch(a.cnt, 1, ATOMIC_RELAXED)
proc getAtomicCount*(a: DataBuffer): int =
proc unsafeGetAtomicCount*(a: DataBuffer): int =
atomicLoad(a.cnt, addr result, ATOMIC_RELAXED)
proc len*(a: DataBuffer): int = a.size
proc toSeq*[T: byte | char](a: DataBuffer, tp: typedesc[T]): seq[T] =
result = newSeq[T](a.len)
copyMem(addr result[0], unsafeAddr a.buf[0], a.len)
proc new*(tp: typedesc[DataBuffer], size: int = 0): DataBuffer =
let cnt = cast[ptr int](allocShared0(sizeof(result.cnt)))
cnt[] = 1

View File

@ -43,8 +43,8 @@ proc thread1(val: int) {.thread.} =
var myBytes = DataBuffer.new(@"hello world")
myBytes2 = myBytes
echo "thread1: sending: ", myBytes, " cnt: ", myBytes.getAtomicCount()
echo "mybytes2: ", myBytes2, " cnt: ", myBytes2.getAtomicCount()
echo "thread1: sending: ", myBytes, " cnt: ", myBytes.unsafeGetAtomicCount()
echo "mybytes2: ", myBytes2, " cnt: ", myBytes2.unsafeGetAtomicCount()
shareVal = myBytes
echo "thread1: sent, left over: ", $myBytes
@ -60,7 +60,8 @@ proc thread2(val: int) {.thread.} =
wait(cond, lock)
echo "thread2: receiving "
let msg: DataBuffer = shareVal
echo "thread2: received: ", msg, " cnt: ", msg.getAtomicCount()
echo "thread2: received: ", msg, " cnt: ", msg.unsafeGetAtomicCount()
check msg.toSeq(char) == @"hello world"
# os.sleep(100)
proc runBasicTest() =