I’m learning as I go through this that there are a lot of undocumented rules about @spawn
.
For example, in @evanfields’s answer, everything works fine. But if you try to use just the for
loop in a .jl file, none of the workers can print to the console, and they don’t iterate more than once, even if the termination condition hasn’t been met; you have to specify the for loop inside a function.
Also, if you try to store a value to a variable declared outside the loop, each while
loop spawned will finish after 1 iteration, with the termination condition still unmet. This causes the program to hang waiting for the RemoteChannel to be ready (if you’re trying to return the value from it with take!
), while it’s not being updated. For example, if you want to have an iterator, both
i = 1
donechannel = RemoteChannel(() -> Channel{Any}(nprocs()))
function findcorner_parallel(n_parallel = nprocs())
for _ in 1:n_parallel
@spawn while !isready(donechannel)
i += 1
...
and
i = 1
donechannel = RemoteChannel(() -> Channel{Any}(nprocs()))
function findcorner_parallel(n_parallel = nprocs())
for _ in 1:n_parallel
@spawn while !isready(donechannel)
j = i
j += 1
...
cause the spawned loops to quit without meeting the termination condition.
Only defining these variables right after the first line of the for loop (or within the spawned while loop, but that won’t do you much good for an iterator) will let the program continue. Maybe this is just the way Julia is supposed to work with variable scope, but it seems very strange to me that I can define new variables based on others originally declared outside the loop (e.g. with a and b already defined, newvar = a + b
inside a spawned loop doesn’t cause any problems), but trying to do anything with a variable set equal to the value of another causes looping to fail silently.
@Janis_Erdmanis How would I check if an individual worker is finished?
Correction: the for loop will actually spawn the while loop correctly even when placed outside a function definition (all spawned workers repeating the calculation until a successful set of inputs is found), but the program will still hang until Enter is pressed if you try to set a variable using take!(donechannel)
, whether you put the assignment inside or outside the for loop.