If your threads are long-living and you are okay to talk in json between 
threads. You can make use of threadproxy library.
    
    
    import strutils
    import nigui
    import os
    import threadproxy
    
    proc workerMain(proxy: ThreadProxy) {.thread.} =
      proxy.onData "task1":
        let n = data.getInt()
        echo "block for ", n
        sleep n               # compute work
        # await sleepAsync n  # IO work
        echo "wake"
        result = %"some text"
      
      waitFor proxy.poll()
    
    proc main() =
      # setup thread
      let proxy = newMainThreadProxy("main")
      proxy.createThread("worker", workerMain)
      
      app.init()
      
      var window = newWindow("Win")
      window.width = 600.scaleToDpi
      window.height = 400.scaleToDpi
      
      var container = newLayoutContainer(Layout_Vertical)
      window.add(container)
      
      var button = newButton("Start")
      var textArea = newTextArea()
      container.add(button)
      container.add(textArea)
      
      button.onClick = proc(event: ClickEvent) =
        let fut = proxy.ask("worker", "task1", %5000)
        fut.addCallback:
          if fut.failed:
            # handler error here
            echo fut.readError.msg
          else:
            let json = fut.read
            textArea.addLine(json.getStr())
      
      window.show()
      
      while true:
        app.processEvents()
        while proxy.process():
          discard
        sleep 16
    
    when isMainModule:
      main()
    
    
    
    
    Run

Reply via email to