Skip to content

Commit 2fd6ec8

Browse files
committed
make string buffer task-local
1 parent 67860dd commit 2fd6ec8

File tree

1 file changed

+8
-14
lines changed

1 file changed

+8
-14
lines changed

src/DecFP.jl

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@ import Printf, Random, SpecialFunctions
77

88
export Dec32, Dec64, Dec128, @d_str, @d32_str, @d64_str, @d128_str, exponent10, ldexp10, sigexp
99

10-
const _buffer = Vector{Vector{UInt8}}()
11-
1210
import Base.promote_rule
1311

1412
# Check exception flags in mask & throw, otherwise returning x;
@@ -60,13 +58,9 @@ function Base.convert(::Type{RoundingMode}, r::DecFPRoundingMode)
6058
end
6159
end
6260

63-
# global vectors must be initialized at runtime (via __init__)
64-
function __init__()
65-
resize!(_buffer, Threads.nthreads())
66-
for i = 1:Threads.nthreads()
67-
_buffer[i] = fill(0x00, 1024)
68-
end
69-
end
61+
# internal task-local buffer for I/O and string conversions
62+
const _STRINGBUFFER_KEY = :DecFP_stringbuffer_abb78e082af23329 # unique key
63+
_stringbuffer() = get!(() -> fill(0x00, 1024), task_local_storage(), _STRINGBUFFER_KEY)::Vector{UInt8}
7064

7165
# status flags from bid_functions.h:
7266
const INVALID = 0x01
@@ -344,16 +338,16 @@ for w in (32,64,128)
344338
end
345339

346340
function tostring(x::$BID)
347-
# fills global _buffer
348-
ccall(($(bidsym(w,"to_string")), libbid), Cvoid, (Ptr{UInt8},$BID,Ref{Cuint}), _buffer[Threads.threadid()], x, zero(Cuint))
341+
# fills global _stringbuffer
342+
ccall(($(bidsym(w,"to_string")), libbid), Cvoid, (Ptr{UInt8},$BID,Ref{Cuint}), _stringbuffer(), x, zero(Cuint))
349343
end
350344

351345
function Base.show(io::IO, x::$BID)
352346
isnan(x) && (print(io, "NaN"); return)
353347
isinf(x) && (print(io, signbit(x) ? "-Inf" : "Inf"); return)
354348
x == 0 && (print(io, signbit(x) ? "-0.0" : "0.0"); return)
355349
tostring(x)
356-
buffer = _buffer[Threads.threadid()]
350+
buffer = _stringbuffer()
357351
if buffer[1] == UInt8('-')
358352
print(io, '-')
359353
end
@@ -415,7 +409,7 @@ for w in (32,64,128)
415409
return Int32(1), Int32(1), signbit(x)
416410
end
417411
tostring(rounded)
418-
buffer = _buffer[Threads.threadid()]
412+
buffer = _stringbuffer()
419413
trailing_zeros = 0
420414
i = 2
421415
while buffer[i] != UInt8('E')
@@ -461,7 +455,7 @@ for w in (32,64,128)
461455
rounded = round(ldexp10(x, n - 1 - normalized_exponent), RoundNearestTiesAway)
462456
rounded_exponent = exponent10(rounded)
463457
tostring(rounded)
464-
buffer = _buffer[Threads.threadid()]
458+
buffer = _stringbuffer()
465459
i = 2
466460
while buffer[i] != UInt8('E')
467461
digits[i - 1] = buffer[i]

0 commit comments

Comments
 (0)