Sanic: Starting sanic in a thread? (ValueError: set_wakeup_fd only works in main thread)

Created on 22 Aug 2017  ·  10Comments  ·  Source: sanic-org/sanic

I have a test.py file where I'm trying to start my sanic server from a separate thread:

def start_server():
    create_app().run(
        port=5000,
        debug=False
    )


def main():
    # start app in background thread
    t = threading.Thread(target=start_server, name='server', daemon=True)
    t.start()
main()

I am however getting the following error:

2017-08-21 22:14:47 - (sanic)[INFO]: Goin' Fast @ http://127.0.0.1:5000
2017-08-21 22:14:47 - (sanic)[ERROR]: Experienced exception while trying to serve
Traceback (most recent call last):
  File "/Users/olalonde/.pyenv/versions/rise/lib/python3.6/site-packages/sanic/app.py", line 595, in run
    serve(**server_settings)
  File "/Users/olalonde/.pyenv/versions/rise/lib/python3.6/site-packages/sanic/server.py", line 520, in serve
    loop.add_signal_handler(_signal, loop.stop)
  File "uvloop/loop.pyx", line 2269, in uvloop.loop.Loop.add_signal_handler (uvloop/loop.c:41305)
ValueError: set_wakeup_fd only works in main thread

Is it not possible to start sanic outside the main thread?

Most helpful comment

Same question

All 10 comments

Same question

Same question

This looks normal, what is the point for running it in separate thread ? Any motivation?

Think of an existing application where you'd want to add a webserver using sanic to receive or return data.

A separate process might be better, as python process can't span multiple CPU cores.

Yeah async frameworks/code are great in a single threaded environment. Single threaded event loop that moves blazing fast. You could use uwsgi, which will spawn multiple workers on differen't CPUs, but your code might have to be tweaked for this. If you are building a simple API with a logical request & response loop uwsgi will work well. See example
[uwsgi]
socket = /tmp/%n.sock
module = werkzeug.testapp:test_app
processes = 4
master = 1

What if I don't want to run a separate process? Should this still work, and if so, how?

@cbess take a look at the _limitations_ when running subprocesses with asyncio :wink:

@cbess take a look at the _limitations_ when running subprocesses with asyncio 😉

Ah! Thanks for the info

Seeing no further discussion, I am closing.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

misakar picture misakar  ·  4Comments

mobdim picture mobdim  ·  4Comments

Souldat picture Souldat  ·  3Comments

1067511899 picture 1067511899  ·  3Comments

jasonab picture jasonab  ·  3Comments