nim-lang - Nim 中类似 Go 的并行性?

标签 nim-lang nimrod

我在 Go 中喜欢但在 Nim 中似乎还找不到的一件事是类似 Go 的“修改后的 CSP”类并行。

我什至还没有开始学习 Nim,现在只是考虑我的选择。我非常喜欢 Go 模型,但 Nim 似乎只有线程。

除了 Nim 中的线程之外,是否有一些包可以合理地用于并行?

有没有计划在 Nim 语言中引入这样的模型,比如 Go 或 Erlang 模型(如果我理解正确的话, Actor 模型),广泛地本着消息传递的精神?

最佳答案

Nim 具有 async/await 类型的协程,用于单线程内的并发
channel 是为线程之间的通信而设计的,但是如果您使用 --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

关于nim-lang - Nim 中类似 Go 的并行性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59843577/

相关文章:

字符串插值

nim-lang - 如何比较模板中的两个 typedesc 是否相等

interface - Nim - 创建实现方法的对象序列

来自 Nim 编译器的 C 字符串文字

nim-lang - 如何更改 Nim 编译器输出文件位置和名称

arrays - 在 Nim 中创建对数组的引用

math - 你如何在 Nimrod 中使用矩阵?

d - Nimrod 中类似 Ada 的类型