我在 Go 中喜欢但似乎在 Nim 中找不到的一件事是类似于 Go 的“修改后的 CSP”类型的并行性。
我什至还没有开始学习 Nim,现在只是考虑我的选择。我非常喜欢 Go 模型,但 Nim 似乎只有线程。
除了 Nim 中的线程之外,还有一些我可以合理地用于并行性的包吗?
本着消息传递的精神,是否有计划在 Nim 语言中引入此类模型,例如 Go 或 Erlang 模型(如果我理解正确的话,演员模型)?
Nim 具有异步/等待类型的协程,用于单线程内的并发
通道是为线程之间的通信而设计的,但是如果您使用 --threads:on 进行编译,则当然可以在协程中使用它们。
下面是两个协程向第三个协程传递消息的简单演示,所有协程都与主线程并发。
import asyncdispatch,strformat,random
var chan: Channel[string] #global declaration
template fakeDelay() = await sleepAsync(rand(2))
proc f(name:string) {.async.} =
for i in 0..6:
echo &"{name}: {i}"
if i==3: chan.send(&"{name}:halfway done")
fakeDelay
proc monitor() {.async.} =
while true:
let tmp = chan.tryRecv
if tmp.dataAvailable:
echo tmp.msg
else: await sleepAsync(1)
proc main() = #main doesn't need to be async
chan.open()
let steve = f("steve")
let mary = f("mary")
asyncCheck monitor() #we don't wait for monitor to finish, so we don't need its Future
echo "main thread continues"
waitFor(steve and mary)
main()
输出:
steve: 0
mary: 0
main thread continues
mary: 1
steve: 1
mary: 2
steve: 2
mary: 3
mary:halfway done
steve: 3
mary: 4
steve:halfway done
mary: 5
steve: 4
mary: 6
steve: 5
steve: 6