Skip to content

Thread safety #4

@mratsim

Description

@mratsim

Just a quick reminder that it might be necessary to use this library in a multithreaded context for example for accounting software with work split across one core per year.

In that case trivial types like arrays should be preferred over sequences if possible, for example here:

proc decode10bitDPD*(dpd: uint16): seq[byte] =
# decode the 3 digits from a densley packed binary of the first 10 bits
# returns 3 bytes containing the digits
# original code from:
# https://github.com/wd5gnr/DensePackDecimal/blob/master/dpd.c
const
FIRST_CHUNK = 0x380.uint16
SECOND_CHUNK = 0x70.uint16
THIRD_CHUNK = 0x7.uint16
var x: uint16 = 0
var y: uint16 = 0
var z: uint16 = 0
if nz(dpd and 8):
if (dpd and 0xE) == 0xE:
case (dpd and 0x60):
of 0:
x = 8 + ((dpd and 0x80) shr 7)
y = 8 + ((dpd and 0x10) shr 4)
z = ((dpd and 0x300) shr 7) or (dpd and 1)
of 0x20:
x = 8 + ((dpd and 0x80) shr 7)
y = ((dpd and 0x300) shr 7) or ((dpd and 0x10) shr 4)
z = 8 + (dpd and 1)
of 0x40:
x = (dpd and 0x380) shr 7
y = 8 + ((dpd and 0x10) shr 4)
z = 8 or (dpd and 1)
of 0x60:
x = 8 + ((dpd and 0x80) shr 7)
y = 8 + ((dpd and 0x10) shr 4)
z = 8 + (dpd and 1)
else:
echo "should never happen (A)"
else:
case (dpd and 0xE):
of 0x8:
x = (dpd and 0x380) shr 7
y = (dpd and 0x70) shr 4
z = 8 + (dpd and 1)
of 0xA:
x = (dpd and 0x380) shr 7
y = 8 + ((dpd and 0x10) shr 4)
z = ((dpd and 0x60) shr 4) or (dpd and 1)
of 0xC:
x = 8 + ((dpd and 0x80) shr 7)
y = (dpd and 0x70) shr 4
z = ((dpd and 0x300) shr 7) or (dpd and 1)
else:
echo "should never happen (B)"
else:
echo "clean"
x = (dpd and FIRST_CHUNK) shr 7
y = (dpd and SECOND_CHUNK) shr 4
z = (dpd and THIRD_CHUNK)
echo "xyz " & $x & " " & $y & " " & $z
result = @[x.byte, y.byte, z.byte]

This also avoids memory allocation which might be a bottleneck if done regularly and which is also problematic for long-running processes as it might lead to memory fragmentation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions