Julia: Transferring data between coroutines (tasks)

I tried to complete two tasks (coroutines) for collaboration, but to no avail. The following is what I have. I never see printlns from source or receiver functions, and the wait () call seems to hang forever. I also tried to make the p (source) task a global variable instead of passing it to sink () as an argument, but that doesn't work either (even if I declare it inside sinke () as global.

This is what I found that I can do very easily with channels and goroutines in Go.

I also experimented with calling yieldto () inside the source () and sink () functions, but I still seem to be ending the dead end.

Anyone who has an example of several tasks sharing data? Ideally, I would have a pipeline or a long chain of tasks.

Thanks in advance for your help.

println("Hello") function source() println("source start") produce("start") produce("stop") end function sink(p::Task) println("sink start") println(consume(p)) println(consume(p)) end a = Task( source ) b = Task( () -> sink(a) ) wait(b) wait(a) println("Goodbye") 
+7
coroutine task julia-lang
source share
1 answer

In Julia, creating a task does not automatically schedule this task. The wait function is not assigned so that you are at a dead end. This is a big difference from Go, where the go operator takes care of all the schedules for you. In julia you need to do a little more work. In particular, use the @sync and @async macros to make this easier.

 @sync begin # @sync will wait for all the contained tasks to terminate. a = @async source() # @async will create and schedule a task for you automatically @async sink(a) end 

You will notice that this does not end either. All printouts occur, but the task does not end. The reason is @sync waiting for task a to complete, but task a was not scheduled. Add the final expense or schedule to your sink function to get task a to write for the last time so that it can end. Or better yet, use a for loop for the task so you always run out of it.

 println("Hello") function source() println("source start") produce("start") produce("stop") println("source end") end function sink(p::Task) println("sink start") for s in p println(s) end println("sink end") end @sync begin a = @async source() @async sink(a) end println("Goodbye") 

Julia's tasks are jointly planned, which basically means that you must ensure that each task is planned independently. Runtime is not going to do this for you. Fortunately, the @sync and @async macros do most of this for you.

+7
source share

All Articles