Julia: How to iterate with Channel

后端 未结 1 1855
小蘑菇
小蘑菇 2020-12-12 01:12

When I run the following code, I get a deprecation saying produce has been replace with channels.

function source(dir)
    filelist = readdir(dir)

    for f         


        
相关标签:
1条回答
  • 2020-12-12 01:47

    Here's one way. Modify your function to accept a channel argument, and put! data in it:

    function source(dir, chnl)
      filelist = readdir(dir)
      for filename in filelist
        name, ext = splitext(filename)
        if ext == ".jld"
          put!(chnl, filename)  % this blocks until "take!" is used elsewhere
        end
      end
    end
    

    Then create your task implicitly using the Channel constructor (which takes a function with a single argument only representing the channel, so we need to wrap the source function around an anonymous function):

    my_channel = Channel( (channel_arg) -> source( pwd(), channel_arg) )
    

    Then, either check the channel is still open (i.e. task hasn't finished) and if so take an argument:

    julia> while isopen( my_channel)
             take!( my_channel) |> println;
           end
    no.jld
    yes.jld
    

    or, use the channel itself as an iterator (iterating over Tasks is becoming deprecated, along with the produce / consume functionality)

    julia> for i in my_channel
             i |> println
           end
    no.jld
    yes.jld
    

    Alternatively you can use @schedule with bind etc as per the documentation, but it seems like the above is the most straightforward way.

    0 讨论(0)
提交回复
热议问题