Skip to content

Parallel killing of agents results in error #670

@Datseris

Description

@Datseris

Describe the bug
When killing agents from a model using Threads.@thread, we get an error.

Minimal Working Example
Notice that the example breaks even if I don't add agents.

# julia --threads=4

using Agents

mutable struct Ag <: AbstractAgent
  id::Int
end

function initialize(;d=0.2, b=0.2)
  model = ABM(Ag, nothing, properties=(b=b, d=d))
  for i in 1:1000
    add_agent!(model)
  end
  return model
end

function model_step!(model::ABM)
  Threads.@threads for ag in collect(allagents(model))
    if rand() < model.b
      add_agent!(model)
    end
    if rand() < model.d
      kill_agent!(ag, model)
    end
  end
end

model = initialize()
step!(model, dummystep, model_step!, 1)
ERROR: TaskFailedException
Stacktrace:
 [1] wait
   @ .\task.jl:334 [inlined]
 [2] threading_run(func::Function)
   @ Base.Threads .\threadingconstructs.jl:38
 [3] macro expansion
   @ .\threadingconstructs.jl:97 [inlined]
 [4] model_step!(model::AgentBasedModel{Nothing, Ag, typeof(Agents.Schedulers.fastest), NamedTuple{(:b, :d), Tuple{Float64, Float64}}, Random.TaskLocalRNG})
   @ Main .\REPL[6]:2
 [5] step!(model::AgentBasedModel{Nothing, Ag, typeof(Agents.Schedulers.fastest), NamedTuple{(:b, :d), Tuple{Float64, Float64}}, Random.TaskLocalRNG}, agent_step!::typeof(dummystep), model_step!::typeof(model_step!), n::Int64, agents_first::Bool)
   @ Agents C:\Users\arvka\.julia\packages\Agents\yf6MH\src\simulations\step.jl:58
 [6] step!(model::AgentBasedModel{Nothing, Ag, typeof(Agents.Schedulers.fastest), NamedTuple{(:b, :d), Tuple{Float64, Float64}}, Random.TaskLocalRNG}, agent_step!::Function, model_step!::Function, n::Int64)
   @ Agents C:\Users\arvka\.julia\packages\Agents\yf6MH\src\simulations\step.jl:48
 [7] top-level scope
   @ REPL[12]:1

    nested task error: UndefRefError: access to undefined reference
    Stacktrace:
     [1] getindex
       @ .\array.jl:861 [inlined]
     [2] (::var"#7#threadsfor_fun#2"{AgentBasedModel{Nothing, Ag, typeof(Agents.Schedulers.fastest), NamedTuple{(:b, :d), Tuple{Float64, Float64}}, Random.TaskLocalRNG}, Vector{Ag}})(onethread::Bool)
       @ Main .\threadingconstructs.jl:84
     [3] (::var"#7#threadsfor_fun#2"{AgentBasedModel{Nothing, Ag, typeof(Agents.Schedulers.fastest), NamedTuple{(:b, :d), Tuple{Float64, Float64}}, Random.TaskLocalRNG}, Vector{Ag}})()
       @ Main .\threadingconstructs.jl:52

Agents.jl version
Version doesn't matter here, anything 5+. Julia 1.7+.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingparallelismFor distributed, threading, or any form of parallelism

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions