Skip to content

Cyvadra/ThreadSafeDicts.jl

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

77 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build status Build Status CI Coverage Status

ThreadSafeDicts.jl

A thread-safe Dict type for Julia programming


Structs and Functions


struct ThreadSafeDict{K, V} <: AbstractDict{K, V}
    dlock::Threads.SpinLock
    d::Dict
    ThreadSafeDict{K, V}() where V where K = new(Threads.SpinLock(), Dict{K, V}())
    ThreadSafeDict{K, V}(itr) where V where K = new(Threads.SpinLock(), Dict{K, V}(itr))
end
ThreadSafeDict() = ThreadSafeDict{Any,Any}()
ThreadSafeDict(pairs::Vector{Pair{K,V}})   

Struct and constructor for ThreadSafeDict. There is one lock per Dict struct. All functions lock this lock, pass arguments to the d member Dict, unlock the spinlock, and then return what is returned by the Dict.

If there are going to be a large number of threads competing to update the Dict, causing most of the threads to be blocked at any given time, you may be better off keeping a Dict in a separate thread which accepts updates via a Channel of Pairs. YMMMV.

getindex(dic::ThreadSafeDict, k)

setindex!(dic::ThreadSafeDict, k, v)

haskey(dic::ThreadSafeDict, k)

get(dic::ThreadSafeDict, k, v)

get!(dic::ThreadSafeDict, k, v)

pop!(dic::ThreadSafeDict)

empty!(dic::ThreadSafeDict)

delete!(dic::ThreadSafeDict, k)

length(dic::ThreadSafeDict)

iterate(dic::ThreadSafeDict)

iterate(dic::ThreadSafeDict, i)

print(io::IO, dic::ThreadSafeDict)



All of the above methods work as in those of the base Dict type. However, they all lock a spinlock prior to passing the arguments to a base Dict within the struct, then unlock the base Dict prior to returning the function call results. Thus, with a single thread the functions are equivalent to those of a base Dict, but with multiple threads thread access to the underlying Dict is serialized per ThreadSafeDict.

Installation

Installation

You may install the package from Github in the usual way, or to install the current master copy:

using Pkg
Pkg.add("http://github.com/wherrera10/ThreadSafeDicts.jl")

About

Thread safe Julia Dict

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Julia 100.0%