问题描述
当我运行以下代码时,我收到一条弃用消息,说生产已被频道替换.
When I run the following code, I get a deprecation saying produce has been replace with channels.
function source(dir)
filelist = readdir(dir)
for filename in filelist
name,ext = splitext(filename)
if ext == ".jld"
produce(filename)
end
end
end
path = "somepathdirectoryhere"
for fname in Task(source(path))
println(fname)
end
我找不到有关如何使用频道执行此操作的示例.我试过创建一个全局频道并使用 put!而不是没有运气的生产.
I cannot find an example on how to do this with channels. I've tried creating a global channel and using put! instead of produce with no luck.
有什么想法吗?
推荐答案
这是一种方法.修改您的函数以接受通道参数,并在其中 put!
数据:
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
然后使用 Channel
构造函数隐式创建您的任务(该构造函数接受一个仅代表通道的单个参数的函数,因此我们需要包装 source
围绕匿名函数的函数):
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
或者,将 channel 本身用作迭代器(迭代 Tasks 以及生产/消费功能已被弃用)
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
或者,您可以根据文档将 @schedule
与 bind
等一起使用,但上面似乎是最直接的方法.
Alternatively you can use @schedule
with bind
etc as per the documentation, but it seems like the above is the most straightforward way.
这篇关于Julia:如何使用 Channel 进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!