S.G*_*ami 0 multithreading crystal-lang
我写了一个程序,一个水晶程序,用 Sieve 计算一个范围内的素数。
#!/usr/bin/env crystal
def sieve(max)
t = Thread.new do
dot, ary, colours = ".", ["\xE2\xA0\x81", "\xE2\xA0\x88", "\xE2\xA0\xA0", "\xE2\xA0\x84"] * 2, [154, 184, 208, 203, 198, 164, 129, 92]
print "\e[?25l"
loop do
ary.size.times do |x|
print("\e[2K#{ary[x]} \e[38;5;#{colours[x]}mPlease Wait#{dot * x}\e[0m\r")
sleep(0.1)
end
end
end
s = [nil, nil] + (2..max).to_a
s.each do |x|
next unless x
break if (sq = x ** 2) > max
(sq..max).step(x) { |y| s[y] = nil }
end
puts "\e[?25h"
s.tap { |x| x.compact! }
end
p sieve(2_000_000).size
Run Code Online (Sandbox Code Playgroud)
问题是当 puts 写筛子时线程没有被杀死。方法sieve(n) 只返回一个数组。然后计算并打印数组大小。您可以看到动画冻结了一段时间,然后一直持续到它被打印并退出。如果我spawn do...end在 spawn 中使用打印暂停,直到计算出筛子。
在 ruby 我曾经做过
t = Thread.new { loop while ... }
<some other time consuming stuff here>
t.kill
return calculated_stuffs
Run Code Online (Sandbox Code Playgroud)
水晶 0.31.1 (2019-10-21)
LLVM:9.0.0 默认目标:x86_64-pc-linux-gnu
如何杀死水晶中的线程?
小智 6
Thread 是 Crystal 内部 API 的一部分,不能直接使用。
好消息是 Crystal 本身支持一种称为CSP的并发模型,其中纤维(轻量级线程)通过线程安全的通道相互发送消息以进行协调。因此,纤维不是通过共享状态进行通信,而是通过通信来共享状态 - 正如他们在golang.
对于您的用例,您可以运行 3 个 Fibers:
这是您的代码的样子
record Result, primes : Array(Int32)
record Tick
alias SieveUpdate = Result | Tick
def monitor(updates : Channel(SieveUpdate)) : Channel(Result)
Channel(Result).new.tap { |done|
spawn do
dot, ary, colours = ".", ["\xE2\xA0\x81", "\xE2\xA0\x88", "\xE2\xA0\xA0", "\xE2\xA0\x84"] * 2, [154, 184, 208, 203, 198, 164, 129, 92]
ary_idx = 0
update_n = 0
print "\e[?25l"
loop do
case value = updates.receive
when Tick
next unless (update_n+=1) % 50 == 0 # lower refresh rate
print("\e[2K#{ary[ary_idx]} \e[38;5;#{colours[ary_idx]}mPlease Wait#{dot * ary_idx}\e[0m\r")
ary_idx = (ary_idx + 1) % ary.size
when Result
puts "\e[?25h"
done.send value
break
end
end
end
}
end
def sieve(max) : Channel(SieveUpdate)
Channel(SieveUpdate).new.tap { |updates|
spawn do
s = [nil, nil] + (2..max).to_a
s.each do |x|
updates.send(Tick.new)
next unless x
break if (sq = x ** 2) > max
(sq..max).step(x) { |y| s[y] = nil }
end
updates.send Result.new(s.compact.as(Array(Int32)))
end
}
end
updates = sieve(2_000_000)
done = monitor(updates)
print done.receive.primes.size
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
289 次 |
| 最近记录: |