# Writing a macro for manual @spawn control

**URL:** <https://discourse.julialang.org/t/writing-a-macro-for-manual-spawn-control/54074>\
**Category:** General Usage\
**Tags:** question\
**Created:** [January 27, 2021, 8:16pm UTC](https://discourse.julialang.org/t/writing-a-macro-for-manual-spawn-control/54074 "2021-01-27T20:16:10Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [January 27, 2021, 8:16pm UTC](https://discourse.julialang.org/t/writing-a-macro-for-manual-spawn-control/54074/1 "2021-01-27T20:16:10Z")

</div>

In some situations we need to limit the number of simultaneously running tasks, for example, when you `@spawn run(...)`, Julia won’t know about CPU usage resulting an over-spawn.

I find something like this helpful:

```julia
julia> x = Threads.Atomic{Int}(0)
Base.Threads.Atomic{Int64}(0)

julia> Threads.@threads for _ = 1:2
           global x
           for i = 1:1000
               Threads.@spawn begin
                   while x[]>6
                       sleep(0.5)
                   end
                   Threads.atomic_add!(x, 1)
                   rand(10000,1000) # replace this with real work load
                   Threads.atomic_sub!(x, 1)
               end
           end
       end

```

In this example I’m willing to use about 2\*6=12 cores (server has 28)

My question is how to make a macro that has a syntax of:

```julia
@limit_spawn x 6 rand(10000,1000)

```

That would generate the corresponding part of the for loop, so one can simply write:

```julia
    for i = 1:1000
        @limit_spawn x 6 rand(10000,1000) # replace this with real work loa
    end

```
