Hi. I need little more help with Nim's async/await. I did two samples: for C# 
and Nim. C#: 
    
    
    using System;
    using System.Threading.Tasks;
    
    namespace AsyncSample
    {
            class MainClass
            {
                    static bool ap1Done = false;
                    static bool ap2Done = false;
                    
                    static int sum (int count)
                    {
                            int result = 0;
                            for (int i = 0; i < (count+1); i++)
                                    result += i;
                            return result;
                    }
                    
                    static Task<int> cbp1() { return Task.Run(() => { return 
sum (100000000); }); }
                    
                    async static void ap1 () {
                            int i = await cbp1 ();
                            Console.WriteLine ("Async Result 1: {0}", i);
                            ap1Done = true;
                    }
                    
                    static Task<int> cbp2() { return Task.Run(() => { return 
sum (10); }); }
                    
                    async static void ap2 ()
                    {
                            int i = await cbp2 ();
                            Console.WriteLine ("Async Result 2: {0}", i);
                            ap2Done = true;
                    }
                    
                    public static void Main (string[] args)
                    {
                            ap1 ();
                            ap2 ();
                            
                            while (!ap1Done || !ap2Done)
                                    System.Threading.Thread.Sleep (100);
                    }
            }
    }
    

result: 
    
    
    Async Result 2: 55
    Async Result 1: 987459712
    
    Press any key to continue...
    

Nim: 
    
    
    import asyncdispatch
    from os import sleep
    
    var ap1Done = false
    var ap2Done = false
    
    proc sum (count: int): int =
      result = 0
      for i in 0..count: result += i
    
    proc cbp1(): Future[int] =
      var retFuture = newFuture[int]("cbp1")
      retFuture.complete(sum(100000000))
      return retFuture
    
    proc ap1() {.async.} =
      var i = await cbp1()
      echo "Async Result 1: " & $i
      ap1Done = true
    
    proc cbp2(): Future[int] =
      var retFuture = newFuture[int]("cbp2")
      retFuture.complete(sum(10))
      return retFuture
    
    proc ap2() {.async.} =
      var i = await cbp2()
      echo "Async Result 2: " & $i
      ap2Done = true
    
    discard ap1()
    discard ap2()
    
    while not ap1Done or not ap2Done:
      sleep(100)
    

result: 
    
    
    Async Result 1: 5000000050000000
    Async Result 2: 55
    

How to compel this code to work asynchronously (without making a threads 
manually)?

Reply via email to