# Threaded function hanging when run through include, but not through REPL

**URL:** https://discourse.julialang.org/t/threaded-function-hanging-when-run-through-include-but-not-through-repl/100105
**Category:** General Usage
**Created:** [June 9, 2023, 1:16pm UTC](https://discourse.julialang.org/t/threaded-function-hanging-when-run-through-include-but-not-through-repl/100105 "2023-06-09T13:16:35Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![f.ij](https://avatars.discourse-cdn.com/v4/letter/f/8491ac/32.png) [@f.ij](https://discourse.julialang.org/u/f.ij)
#### Post date: [June 9, 2023, 1:16pm UTC](https://discourse.julialang.org/t/threaded-function-hanging-when-run-through-include-but-not-through-repl/100105/1 "2023-06-09T13:16:35Z")

</div>

I have the following code:

```julia
const vec = rand(10000)
const shouldrun = Ref(true)

uselessalgo(vec) = vec .= rand(10000)

function uselessLoop(vec, shouldrun)
    while shouldrun[]
        uselessalgo(vec)
        GC.safepoint()
    end
end

function spawnUselessLoop(vec, shouldrun)
    println("Starting loop...")
    shouldrun[] = true
    println("Spawning thread...")
    Threads.@spawn uselessLoop(vec, shouldrun)
    println("Sleeping")
    sleep(1)
    println("Stopping loop...")
    shouldrun[] = false
end

spawnUselessLoop(vec, shouldrun)

```

If I save this as a file and run it through `include("filename")`, then it will almost certainly hang for me. First of all, I’m not sure exactly why, I thought `GC.safepoint()` should prevent this. Can anybody explain this to me?  
Then, if I first comment out the function call, and manually call it by typing it in in the REPL, it will almost never hang for me. Why does there seem to be a difference?

---

<div class="post-metadata">

### Author: ![Ralph\_Smith](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ralph_smith/32/10344_2.png) [@Ralph\_Smith](https://discourse.julialang.org/u/Ralph_Smith)
#### Post date: [June 9, 2023, 3:16pm UTC](https://discourse.julialang.org/t/threaded-function-hanging-when-run-through-include-but-not-through-repl/100105/2 "2023-06-09T15:16:07Z")

</div>

It apparently hangs in the interface to `libuv` (which handles simple IO and the `sleep` timer), so congratulations on finding a bug in Base concurrency. There seems to be a race between `@spawn` and some lock used by the interface. Care to file an issue?

The problem **appears** to go away if one adds an interactive thread (in v1.9), or interposes some computations before the call to `println` just after `@spawn`.

Incidentally, the `safepoint` call is not helpful here since `rand` allocates.
