# I get a dead lock with only one lock

**URL:** https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788
**Category:** General Usage
**Created:** [March 31, 2022, 8:50am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788 "2022-03-31T08:50:09Z")
**Posts on this page:** 16
**Page:** 1

<div class="post-metadata">

### Author: ![Impressium](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/impressium/32/19575_2.png) [@Impressium](https://discourse.julialang.org/u/Impressium)
#### Post date: [March 31, 2022, 8:50am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/1 "2022-03-31T08:50:09Z")

</div>

Hi all 🙂

I’ve got the following in one of my pkgs. I put a print before and after. But one in 100 run it just stops there and does not print the second time. I’m kinda clueless how to debug this problem even more and fix it. Seems like correct Julia code for me. (PS: I don’t get the issue with the example code in the repl)

```julia
julia> l = ReentrantLock()
ReentrantLock(nothing, Base.GenericCondition{Base.Threads.SpinLock}(Base.InvasiveLinkedList{Task}(nothing, nothing), Base.Threads.SpinLock(0)), 0)

julia> d = Dict()
Dict{Any, Any}()

julia> lock(l) do
           d[:key] = :value
       end
:value

```

Cheers

Edit:  
Julia Version 1.6.3 and 1.7.2

---

<div class="post-metadata">

### Author: ![lawless-m](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lawless-m/32/30869_2.png) [@lawless-m](https://discourse.julialang.org/u/lawless-m)
#### Post date: [March 31, 2022, 8:55am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/2 "2022-03-31T08:55:45Z")

</div>

bit hard to help when your MWE works just fine 🙂

even this without deadlock

```julia
for i in 1:1_000_000
       lock(l) do 
          print("a");
          d[:key] = :value
       end
end

```

---

<div class="post-metadata">

### Author: ![goerch](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/goerch/32/29122_2.png) [@goerch](https://discourse.julialang.org/u/goerch)
#### Post date: [March 31, 2022, 8:55am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/3 "2022-03-31T08:55:59Z")

</div>

Your example looks like serial code. Why use a lock then in the first place?

---

<div class="post-metadata">

### Author: ![Impressium](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/impressium/32/19575_2.png) [@Impressium](https://discourse.julialang.org/u/Impressium)
#### Post date: [March 31, 2022, 9:04am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/4 "2022-03-31T09:04:35Z")

</div>

```julia

Base.@kwdef struct _ActiveBars
    dict::Dict{Int, BarManager} = Dict{Int, BarManager}()
    last_id::Threads.Atomic{Int} = Threads.Atomic{Int}(1)
    lock::ReentrantLock = ReentrantLock()
end

const _ACTIVE_BARS = _ActiveBars()

function _start(; 
    bar_structure::Type{BarStructureType},
    initial_bars::Union{Vector{Dict{UniqueSymbol{ExchangeSymbolType},BarStructureType}}, Nothing},
    interval_between_bars::Second,
    bar_calculation::Function,    

    unique_symbols::Set{UniqueSymbol{ExchangeSymbolType}},
    quote_change_types::Vector{Messages.QuoteChangeTypes.QuoteChangeType},

    bar_output::Function,

    include_with_these_last_trade_conditioncodes::Vector{String},
    drop_message::Function,
    history_length::Int,
    future_length::Int,
    active_bars::_ActiveBars = _ACTIVE_BARS
)::Int where {BarStructureType, ExchangeSymbolType <: AbstractExchangeSymbol} 

    id = Threads.atomic_add!(active_bars.last_id, 1)

    bar_manager = BarManager{BarStructureType, ExchangeSymbolType}(;
        name = "bar_$id",
        bar_output,
        bar_calculation,    

        unique_symbols,
        quote_change_types,
        initial_bars,
        interval_between_bars,
        include_with_these_last_trade_conditioncodes,
        drop_message,
        history_length,
        future_length,
    )

    _start(bar_manager)

    lock(active_bars.lock) do 
        active_bars.dict[id] = bar_manager
    end

    return id
end

function _stop(
    id::Int;
    active_bars::_ActiveBars = _ACTIVE_BARS
)::Nothing

    bar_manager = lock(active_bars.lock) do
        pop!(
            active_bars.dict,
            id,
            nothing
        )
    end

    isnothing(bar_manager) && error()
    
    _stop(bar_manager)

    return
end

```

That’s the code. I want to make sure that start and stop can be called from different threads… That’s why I use the lock

---

<div class="post-metadata">

### Author: ![Impressium](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/impressium/32/19575_2.png) [@Impressium](https://discourse.julialang.org/u/Impressium)
#### Post date: [March 31, 2022, 9:05am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/5 "2022-03-31T09:05:39Z")

</div>

The example problem works for me as well… That’s the problem

---

<div class="post-metadata">

### Author: ![Impressium](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/impressium/32/19575_2.png) [@Impressium](https://discourse.julialang.org/u/Impressium)
#### Post date: [March 31, 2022, 9:06am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/6 "2022-03-31T09:06:28Z")

</div>

That’s just the example. I want to make sure that start and stop are thread safe

---

<div class="post-metadata">

### Author: ![goerch](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/goerch/32/29122_2.png) [@goerch](https://discourse.julialang.org/u/goerch)
#### Post date: [March 31, 2022, 9:16am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/7 "2022-03-31T09:16:30Z")

</div>

Depending on the number of `_ActiveBars` instances floating around you could have more than one lock?

To verify if locking is really the problem here you could use `Base.trylock`?

---

<div class="post-metadata">

### Author: ![Impressium](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/impressium/32/19575_2.png) [@Impressium](https://discourse.julialang.org/u/Impressium)
#### Post date: [March 31, 2022, 9:32am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/8 "2022-03-31T09:32:19Z")

</div>

Should only be one. Because of the const in front of it

---

<div class="post-metadata">

### Author: ![Sukera](https://avatars.discourse-cdn.com/v4/letter/s/ce7236/32.png) [@Sukera](https://discourse.julialang.org/u/Sukera)
#### Post date: [March 31, 2022, 9:40am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/9 "2022-03-31T09:40:51Z")

</div>

> [@Impressium](#):
>
> `_start(bar_manager)`

What does this ultimately call? As far as I can tell, it’s not part of the code you posted.

---

<div class="post-metadata">

### Author: ![Impressium](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/impressium/32/19575_2.png) [@Impressium](https://discourse.julialang.org/u/Impressium)
#### Post date: [March 31, 2022, 10:16am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/10 "2022-03-31T10:16:07Z")

</div>

```julia
function _start(bar_manager::BarManager)::Nothing
    
    bar_manager.is_running[] = true

    _HistoryManagement.start(bar_manager.history)

    bar_manager.market_subscribtion_id[] = Markets.subscribe(
        (message) -> _HistoryManagement.getting_messages(bar_manager.history, message),
        [
            Markets.SymbolSubscriptionInfo(;
                unique_symbol = unique_symbol,
                quote_change_types = bar_manager.history.quote_change_types
            )
            for unique_symbol in bar_manager.history.unique_symbols |> values
        ]
    )

    bar_manager.producing_task[] = Utils.@my_spawn _start_producing_bars!(bar_manager)

    return
end

```

---

<div class="post-metadata">

### Author: ![goerch](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/goerch/32/29122_2.png) [@goerch](https://discourse.julialang.org/u/goerch)
#### Post date: [March 31, 2022, 10:47am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/11 "2022-03-31T10:47:54Z")

</div>

> [@Impressium](#):
>
> I put a print before and after. But one in 100 run it just stops there and does not print the second time. I’m kinda clueless how to debug this problem even more and fix it.

Here is what I would try assuming a problem in my code(and it would be a pain in the …): first I’d try to make the problem more reproducible mainly increasing the CPU workload artificially (eliminating file I/O and network I/O, increasing number of threads etc.). Then I’d try to produce a trace of the multi threading activity (spawns, joins, locks, channel read/write). With a bit of luck one of these traces could reveal a deadlock…

There could be chance that you are encountering a [Julia problem](https://github.com/JuliaLang/julia/search?q=deadlock&type=issues), but even in this case the steps above could help finding a reproducer…

---

<div class="post-metadata">

### Author: ![Impressium](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/impressium/32/19575_2.png) [@Impressium](https://discourse.julialang.org/u/Impressium)
#### Post date: [March 31, 2022, 10:54am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/12 "2022-03-31T10:54:41Z")

</div>

I tried it now with `Base.trylock`. Same behavior - one in 100 stops

---

<div class="post-metadata">

### Author: ![goerch](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/goerch/32/29122_2.png) [@goerch](https://discourse.julialang.org/u/goerch)
#### Post date: [March 31, 2022, 11:04am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/13 "2022-03-31T11:04:17Z")

</div>

> [@Impressium](#):
>
> I tried it now with `Base.trylock` . Same behavior - one in 100 stops

But `trylock` doesn’t wait: it returns `false` if the lock is not available.

---

<div class="post-metadata">

### Author: ![Impressium](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/impressium/32/19575_2.png) [@Impressium](https://discourse.julialang.org/u/Impressium)
#### Post date: [March 31, 2022, 11:08am UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/14 "2022-03-31T11:08:01Z")

</div>

The strange part about it. Maybe I did something wrong.

```julia
    if Base.trylock(active_bars.lock)
        active_bars.dict[id] = bar_manager
        unlock(active_bars.lock)
    else 
        error("Not able to lock")
    end
    # lock(active_bars.lock) do 
    # active_bars.dict[id] = bar_manager
    # end

```

---

<div class="post-metadata">

### Author: ![goerch](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/goerch/32/29122_2.png) [@goerch](https://discourse.julialang.org/u/goerch)
#### Post date: [March 31, 2022, 12:45pm UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/15 "2022-03-31T12:45:09Z")

</div>

> [@Impressium](#):
>
> Maybe I did something wrong.

No, I’d extend it to something like

```julia
    l = ReentrantLock()
    retries = 5
    while retries > 0
        if Base.trylock(l)
            unlock(l)
            break
        end
        sleep(1)
        @info "retrying"
        retries -= 1
    end
    if retries == 0
        @error "deadlock?"
    end

```

Couple of more questions:

- do you see any Julia activity in your system monitor when the problem occurs?
- did you check with different Julia versions?

---

<div class="post-metadata">

### Author: ![Impressium](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/impressium/32/19575_2.png) [@Impressium](https://discourse.julialang.org/u/Impressium)
#### Post date: [March 31, 2022, 6:13pm UTC](https://discourse.julialang.org/t/i-get-a-dead-lock-with-only-one-lock/78788/16 "2022-03-31T18:13:44Z")

</div>

Quick update… it wasn’t the lock, but the `start` function bevor. But still don’t know why it’s stops completely…

Thank you all
