# Thread-safe implementation for simple counter/mean

**URL:** <https://discourse.julialang.org/t/thread-safe-implementation-for-simple-counter-mean/137542>\
**Category:** General Usage\
**Tags:** question, multithreading\
**Created:** [June 10, 2026, 11:57am UTC](https://discourse.julialang.org/t/thread-safe-implementation-for-simple-counter-mean/137542 "2026-06-10T11:57:00Z")\
**Posts on this page:** 2\
**Page:** 2

<div class="post-metadata">

**Author:** ![jakobnissen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jakobnissen/32/13477_2.png) [@jakobnissen](https://discourse.julialang.org/u/jakobnissen)\
**Post date:** [June 11, 2026, 3:34pm UTC](https://discourse.julialang.org/t/thread-safe-implementation-for-simple-counter-mean/137542/21 "2026-06-11T15:34:17Z")

</div>

It’s just for API convenience. If you use a raw `ReentrantLock`, you need to pass around the lock and the thing it locks together, and remember which lock goes with which data. By using `Lockable`, the lock and the thing it locks is wrapped in a struct so you can’t forget that the data is protected by a lock, or access the data without the lock, or accidentally mix up multiple locks.

So, it’s API protection against mistakes.

---

<div class="post-metadata">

**Author:** ![foobar\_lv2](https://avatars.discourse-cdn.com/v4/letter/f/ee59a6/32.png) [@foobar\_lv2](https://discourse.julialang.org/u/foobar_lv2)\
**Post date:** [June 11, 2026, 3:58pm UTC](https://discourse.julialang.org/t/thread-safe-implementation-for-simple-counter-mean/137542/22 "2026-06-11T15:58:04Z")

</div>

> [@jakobnissen](#):
>
> For `ReentrantLock` specifically, task 2 will enter a short loop where it will repeatedly try to take the lock (i.e. it will spin).

That would be the expected thing, and what the source-code comments suggest.

It is not what julia is actually doing [julia/base/lock.jl at bcda9827f52772efc3122230fc47220bdfed8756 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/blob/bcda9827f52772efc3122230fc47220bdfed8756/base/lock.jl#L194)

The source-code comment claims that we spin for the lock, but we don’t. Instead we repeatedly call `Base.yield()`, which basically tells the julia scheduler to find other work. If the julia scheduler found other work, then we pay the full cost of context switching; if it didn’t, then it will try to take the lock again (a spin with extra steps).

My personal thought is that this current procedure sucks. We should spin for some time (aka try again after some `pause` instructions). Then we should not `Base.yield()`, and instead immediately park on the lock. We tell the scheduler that we’re blocked, but refuse to tell it by what we’re blocked.

[Previous page](https://discourse.julialang.org/t/thread-safe-implementation-for-simple-counter-mean/137542.md?page=1)
