I have set up an AsyncHttpServer running fine (and blocking everything else):
import asyncdispatch, asynchttpserver, threadpool
import strformat
const port = 18967
proc startServer() {.async.} =
var server = newAsyncHttpServer()
proc handler(req: Request) {.async,gcsafe.} =
let headers = newHttpHeaders()
await req.respond(404.HttpCode, req.url.path, headers)
try:
echo ":: Starting server on port " & $(port) & "...\n"
server.listen(Port(port))
while true:
if server.shouldAcceptRequest():
await server.acceptRequest(handler)
else:
await sleepAsync(500)
except:
let e = getCurrentException()
echo ":: Server message: " & e.msg
server.close()
proc startSyncServer() =
waitFor startServer()
startSyncServer()
Now, if we replace the last line with spawn startSyncServer(), then everything works fine. But that's not the end of it, since this is nothing but a simple isolated test.
When I'm trying to replicate the exact same thing in the complete codebase, I keep getting the following error:
Error: closure in spawn environment is not allowed
spawn startSyncServer()
^
And no matter what --verbosity level I set, I cannot figure out where the error stems from - or if it implies that suddenly startSyncServer is considered a closure.
Honestly, the "real" codebase implementation and the one above have practically zero differences - other than than the exact same code is wrapped itself in a proc() (could that be the issue?).
Any help will be more than appreciated - I've been banging my head against the wall for days with this thing!
Haven't tried with spawn, but the way I run async code within threads is something like this:
var thread: Thread[void]
proc asyncStuff() {.async.} =
<async stuff goes here and uses `await`>
proc myThread() {.thread.} =
asyncCheck asyncStuff()
runForever()
createThread(thread, myThread)
Of course that is for an async procedure which runs forever. If you had used waitFor asyncStuff() it should do the same thing.
Now another question is "why are you mixing async and threads?". In general this isn't something you should need all that often.