# Does @threads not allow iteration over Dict()?

**URL:** <https://discourse.julialang.org/t/does-threads-not-allow-iteration-over-dict/33912>\
**Category:** New to Julia\
**Tags:** question\
**Created:** [January 29, 2020, 1:11am UTC](https://discourse.julialang.org/t/does-threads-not-allow-iteration-over-dict/33912 "2020-01-29T01:11:41Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sijun](https://avatars.discourse-cdn.com/v4/letter/s/b2d939/32.png) [@Sijun](https://discourse.julialang.org/u/Sijun)\
**Post date:** [January 29, 2020, 1:11am UTC](https://discourse.julialang.org/t/does-threads-not-allow-iteration-over-dict/33912/1 "2020-01-29T01:11:41Z")

</div>

I have no idea why the following code errors:

```julia
using Base.Threads

A = Dict{Int, Vector{Float64}}()
# A = rand(10, 10) # OK

foreach(i->A[i] = rand(10), 1:10)

@threads for i in eachindex(A) # ERROR: TaskFailedException in case that A is a Dict()
    sum(A[i])
end

```

> ERROR: TaskFailedException:  
> MethodError: no method matching unsafe\_getindex(::Base.KeySet{Int64,Dict{Int64,Array{Float64,1}}}, ::Int64)  
> Closest candidates are:  
> unsafe\_getindex(::StepRangeLen{T,#s66,#s65} where #s65\<:Base.TwicePrecision where #s66\<:Base.TwicePrecision, ::Integer) where T at twiceprecision.jl:447  
> unsafe\_getindex(::StepRangeLen{T,R,S} where S where R, ::Integer) where T at range.jl:647  
> unsafe\_getindex(::LinRange, ::Integer) at range.jl:657

It seems like that @threads does not allow iteration over Dict(); If `A` is an array e.g., `A = rand(10, 10)` no such error occurs.

---

<div class="post-metadata">

**Author:** ![tro3](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tro3/32/12355_2.png) [@tro3](https://discourse.julialang.org/u/tro3)\
**Post date:** [January 29, 2020, 4:58am UTC](https://discourse.julialang.org/t/does-threads-not-allow-iteration-over-dict/33912/2 "2020-01-29T04:58:20Z")

</div>

Yeah, the internal implementation of the `@threads` has trouble with some generators and the like (in this case, a `KeySet`) due to the `unsafe_getindex` usage. Try this:

```julia
@threads for i in collect(eachindex(A)) # Turns the KeySet into a Vector first
    sum(A[i])
end

```

---

<div class="post-metadata">

**Author:** ![Sijun](https://avatars.discourse-cdn.com/v4/letter/s/b2d939/32.png) [@Sijun](https://discourse.julialang.org/u/Sijun)\
**Post date:** [January 29, 2020, 5:12am UTC](https://discourse.julialang.org/t/does-threads-not-allow-iteration-over-dict/33912/3 "2020-01-29T05:12:11Z")

</div>

How straightforward but clever the idea is! Why didn’t such an idea come to my mind?
