Go-like parallelism in Nim?
Asked Answered
B

1

7

One thing I like in Go and can't seem to find in Nim yet is Go-like, "modified CSP" kind of parallelism.

I have not even started learning Nim yet, just considering my options for now. I quite liked the Go model, but Nim seems to have threads only.

Is there some package that I can reasonably use for parallelism other than threads in Nim?

Are there any plans to introduce such model(s) in Nim language, like Go or Erlang model (actor model if I understand correctly), broadly in the spirit of message passing?

Berns answered 21/1, 2020 at 14:45 Comment(1)
For message passing: nim-lang.org/docs/channels.html ?Archer
C
9

Nim has async/await type coroutines for concurrency within a single thread

Channels are designed for communication between threads, but if you compile with --threads:on it's certainly possible to use them in coroutines.

Here's a simple demonstration of two coroutines passing messages to a third, all concurrent with the main thread.

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()

output:

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
Collettecolletti answered 9/9, 2020 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.