6 Star 28 Fork 14

Julia语言程序设计 / bookexamples

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
demo_mconsumer.jl 1.07 KB
一键复制 编辑 原始数据 按行查看 历史
魏坤 提交于 2018-08-18 11:48 . 适配v1.0
using Distributed
const jobs = Channel{Int}(32);
const results = Channel{Tuple}(32);
function do_work() # 消费者
for job_id in jobs # 用for循环从输入通道jobs中读取任务数据
exec_time = rand()
sleep(exec_time) # 用sleep模拟处理过程
put!(results, (job_id, exec_time)) # 将结果放入输出通道results中
end
end
function make_jobs(n) # 生产者
for i in 1:n
put!(jobs, i) # 往任务通道jobs中放入数据
end
end
n = 12;
@async make_jobs(n); # 将生产者加入任务调度中
for i in 1:4
@async do_work() # 异步地启动4个消费者,实现并行消费
end
@elapsed while n > 0 # 打印消费者执行后的结果
job_id, exec_time = take!(results); # 从结果通道中提取数据
println("$job_id finished in $(round(exec_time,digits=2)) seconds")
global n = n - 1
end
Julia
1
https://gitee.com/juliaprog/bookexamples.git
git@gitee.com:juliaprog/bookexamples.git
juliaprog
bookexamples
bookexamples
master

搜索帮助