I learnt about ReentrantLock
in JuMP’s doc.
function a_correct_way_to_build_with_multithreading()
model = Model()
@variable(model, x[1:10])
my_lock = Threads.ReentrantLock()
Threads.@threads for i in 1:10
con = @build_constraint(x[i] <= i)
Threads.lock(my_lock) do
add_constraint(model, con)
end
end
return model
end
This example reveals some idea, but it is not thorough. Therefore I have a question.
- is this line
my_lock = Threads.ReentrantLock()
a one-off operation, or should we write it every time immediately beforeThreads.@threads for i in 1:10
?
Take a simpler analogous example. This is a one-off case
container = Vector{Int}(undef, 3) # one-off is enough
while true
# here we don't need to allocate container once more
# we also don't need to reset some state, because they are irrelevant
Threads.@threads for i in 1:3
container[i] = i
end
end
This is a case we must execute every time before for
flag = falses(3) # allocate
flag .= false # reset the state
while true
flag .= false # we must reset the state
Threads.@threads for i in 1:3
if flag[i] == false
flag[i] = true
else
error()
end
end
end