Hi, try this (works for me) and I put some comments in it:
    
    
    import locks
    import os
    import asyncdispatch
    import asynchttpserver, asyncdispatch
    
    var L: Lock
    
    type Context = ref object {.pure.}
      num: int
      str: string
    
    proc th(ctxP: pointer) {.thread.} =
      var server = newAsyncHttpServer()
      proc cb(req: Request) {.async.} =
        var idx: int = 0
        if not tryAcquire(L): return
        var ctx = cast[ptr Context](ctxP) # never cast ptr to ref
                                          # within different thread
       # GC_ref ctx # ???? not needed because ctx is not owned by this thread
        ctx[].num.inc()
        idx = ctx[].num
        sleep(200) # sleep while locking to get the: "could not acquire lock" 
msg
       # GC_unref ctx # ????
        release(L)
        await req.respond(Http200, "Hello World " & $idx)
      proc aprint(): Future[void] {.async.} =
        while true:
          echo "hello"
          await sleepAsync 1000
      asyncCheck aprint()
      asyncCheck server.serve(Port(8080), cb)
      runForever()
    
    initLock(L)
    let ctx = Context(num: 0, str: "")
    var ctxP = ctx.unsafeAddr
    # GC_ref ctx # parentthread is owner of ctx (I think its not needed because 
of the
    # endless loop)
    var networkThread: Thread[pointer]
    networkThread.createThread(th, ctxP)
    while true:
      if not tryAcquire(L):
        echo "could not aquire lock"
        sleep(50)
        continue
      ctx.num.inc
      echo(ctx.num)
      release(L)
      sleep(2500)
    
    
    Run

Reply via email to