# Can I guarentee two tasks run on different threads?

**URL:** <https://discourse.julialang.org/t/can-i-guarentee-two-tasks-run-on-different-threads/114858>\
**Category:** General Usage\
**Created:** [May 28, 2024, 5:22pm UTC](https://discourse.julialang.org/t/can-i-guarentee-two-tasks-run-on-different-threads/114858 "2024-05-28T17:22:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Larbino1](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/larbino1/32/37831_2.png) [@Larbino1](https://discourse.julialang.org/u/Larbino1)\
**Post date:** [May 28, 2024, 5:22pm UTC](https://discourse.julialang.org/t/can-i-guarentee-two-tasks-run-on-different-threads/114858/1 "2024-05-28T17:22:23Z")

</div>

I have what I though would be a simple problem but have been disappointed in julia’s ability regarding it. I have a program that send a bunch of packets over UDP. I want to receive them in julia as follows:

Have a “listener thread” that repeatedly calls `recv(...)` to read a new UDP packet and update some data (protected by a lock)

```julia
using Base.Threads
using Sockets

socket = UDPSocket()
bind(socket, Sockets.localhost, 49691)
lck = ReentrantLock()

data = Vector{UInt8}()
timestamp = Ref(time())

listener = @spawn begin
    println("Thread: $(Threads.threadid())")
    while true
        newdata = recv(socket)
        lock(lck) do
            copy!(data, newdata)
            timestamp[] = time()
        end
    end    
end

```

Have a “Main thread” that will access the shared data.

```julia
println("Thread: $(Threads.threadid())")
while true
    Libc.systemsleep(0.05) # Do stuff
    lock(lck) do
        if timestamp[] < (time() - 0.2)
            @warn "data too old"
        else
            println("Success")
        end
    end
end

```

The problem I have is that despite running julia with 4 threads, the listener-thread decides to run on thread 1, the same as the main thread. Therefore recv is not called while the main task is running.

As far as I can tell there is NO WAY to ensure that these two tasks run on different threads…

Unfortunately, the example I have given above DOES NOT reproduce the problem I have described… hopefully it helps explain my goal though. Can anyone help? 😢

---

<div class="post-metadata">

**Author:** ![Oscar\_Smith](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oscar_smith/32/25343_2.png) [@Oscar\_Smith](https://discourse.julialang.org/u/Oscar_Smith)\
**Post date:** [May 28, 2024, 5:25pm UTC](https://discourse.julialang.org/t/can-i-guarentee-two-tasks-run-on-different-threads/114858/2 "2024-05-28T17:25:21Z")

</div>

Julia 1.10 adds an interactive threadpool which should let you do what you want. See [Multi-Threading · The Julia Language](https://docs.julialang.org/en/v1/manual/multi-threading/#man-threadpools) for the docs
