-
Notifications
You must be signed in to change notification settings - Fork 57
Reduce memory & redundant work for concurrent TimeZones construction #356
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
NHDaly
wants to merge
6
commits into
JuliaTime:master
Choose a base branch
from
NHDaly:nhd/share-cache
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
5bffed5
Reduce memory & redundant work for concurrent TimeZones construction
NHDaly 6c0d3ea
Add `@lock` macro on julia 1.0
NHDaly beacaaa
PR Feedback from review.
NHDaly 96252ab
Merge branch 'master' into nhd/share-cache
NHDaly 4f444eb
Drop compat for `Base.@lock` now that we're on julia 1.6+ as LTS :)
NHDaly 0258929
PR feedback
NHDaly File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,12 @@ | |
# to the cache, while still being thread-safe. | ||
const THREAD_TZ_CACHES = Vector{Dict{String,Tuple{TimeZone,Class}}}() | ||
|
||
# Holding a lock during construction of a specific TimeZone prevents multiple Tasks (on the | ||
# same or different threads) from attempting to construct the same TimeZone object, and | ||
# allows them all to share the result. | ||
const TZ_CACHE_MUTEX = ReentrantLock() | ||
const TZ_CACHE_FUTURES = Dict{String,Channel{Tuple{TimeZone,Class}}}() # Guarded by: TZ_CACHE_MUTEX | ||
|
||
# Based upon the thread-safe Global RNG implementation in the Random stdlib: | ||
# https://github.com/JuliaLang/julia/blob/e4fcdf5b04fd9751ce48b0afc700330475b42443/stdlib/Random/src/RNGs.jl#L369-L385 | ||
@inline _tz_cache() = _tz_cache(Threads.threadid()) | ||
|
@@ -19,10 +25,22 @@ const THREAD_TZ_CACHES = Vector{Dict{String,Tuple{TimeZone,Class}}}() | |
end | ||
@noinline _tz_cache_length_assert() = @assert false "0 < tid <= length(THREAD_TZ_CACHES)" | ||
|
||
function _reset_tz_cache() | ||
# ensures that we didn't save a bad object | ||
function _init_tz_cache() | ||
resize!(empty!(THREAD_TZ_CACHES), Threads.nthreads()) | ||
end | ||
# ensures that we didn't save a bad object | ||
function _reset_tz_cache() | ||
# Since we use thread-local caches, we spawn a task on _each thread_ to clear that | ||
# thread's local cache. | ||
Threads.@threads for i in 1:Threads.nthreads() | ||
@assert Threads.threadid() === i "TimeZones.TZData.compile() must be called from the main, top-level Task." | ||
empty!(_tz_cache()) | ||
end | ||
@lock TZ_CACHE_MUTEX begin | ||
empty!(TZ_CACHE_FUTURES) | ||
end | ||
return nothing | ||
end | ||
|
||
""" | ||
TimeZone(str::AbstractString) -> TimeZone | ||
|
@@ -68,20 +86,40 @@ function TimeZone(str::AbstractString, mask::Class=Class(:DEFAULT)) | |
# Note: If the class `mask` does not match the time zone we'll still load the | ||
# information into the cache to ensure the result is consistent. | ||
tz, class = get!(_tz_cache(), str) do | ||
tz_path = joinpath(TZData.COMPILED_DIR, split(str, "/")...) | ||
|
||
if isfile(tz_path) | ||
open(deserialize, tz_path, "r") | ||
elseif occursin(FIXED_TIME_ZONE_REGEX, str) | ||
FixedTimeZone(str), Class(:FIXED) | ||
elseif !isdir(TZData.COMPILED_DIR) || isempty(readdir(TZData.COMPILED_DIR)) | ||
# Note: Julia 1.0 supresses the build logs which can hide issues in time zone | ||
# compliation which result in no tzdata time zones being available. | ||
throw(ArgumentError( | ||
"Unable to find time zone \"$str\". Try running `TimeZones.build()`." | ||
)) | ||
# Even though we're using Thread-local caches, we still need to lock during | ||
# construction to prevent multiple tasks redundantly constructing the same object, | ||
# and potential thread safety violations due to Tasks migrating threads. | ||
# NOTE that we only grab the lock if the TZ doesn't exist, so the mutex contention | ||
# is not on the critical path for most constructors. :) | ||
constructing = false | ||
# We lock the mutex, but for only a short, *constant time* duration, to grab the | ||
# future for this TimeZone, or create the future if it doesn't exist. | ||
future = @lock TZ_CACHE_MUTEX begin | ||
get!(TZ_CACHE_FUTURES, str) do | ||
constructing = true | ||
Channel{Tuple{TimeZone,Class}}(1) | ||
end | ||
end | ||
if constructing | ||
tz_path = joinpath(TZData.COMPILED_DIR, split(str, "/")...) | ||
|
||
t = if isfile(tz_path) | ||
open(deserialize, tz_path, "r") | ||
elseif occursin(FIXED_TIME_ZONE_REGEX, str) | ||
FixedTimeZone(str), Class(:FIXED) | ||
elseif !isdir(TZData.COMPILED_DIR) || isempty(readdir(TZData.COMPILED_DIR)) | ||
# Note: Julia 1.0 supresses the build logs which can hide issues in time zone | ||
# compliation which result in no tzdata time zones being available. | ||
throw(ArgumentError( | ||
"Unable to find time zone \"$str\". Try running `TimeZones.build()`." | ||
)) | ||
else | ||
throw(ArgumentError("Unknown time zone \"$str\"")) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Exceptions while constructing will cause threads to be blocked upon waiting for a channel that will never be populated |
||
end | ||
|
||
put!(future, t) | ||
else | ||
throw(ArgumentError("Unknown time zone \"$str\"")) | ||
fetch(future) | ||
end | ||
end | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How is this guaranteed when calling
compile/_reset_tz_cache
from the main task?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't remember / understand the reason, but the
Threads.@threads
macro only works from the top-level task.The behavior of
@threads
is that it evenly divides the for-loop across the number of threads, so if you have exactlynthreads()
iterations, exactly one iteration will go on each thread.It only works from thread 1, for reasons i can't quite remember, but so this basically means you have to start it from the main Task. (I didn't remember that it was a "thread 1" requirement - i thought it was actually a "main Task" requirement.. i can consider changing the assertion message, perhaps? But i think it's easier guidance to say "don't call this concurrently, dude")