0

I have a server running in the main thread, and a background process to impair network conditions in another thread. The server can only run in the main thread.

if __name__ == "__main__":
    args = parse_args()

    net_thread = Thread(target=run_net, args=(args,))
    net_thread.start()

    run_server(args.host, args.port, args.play_from, args.verbose, args.cert_file)

I want to rethrow any exceptions the background thread throws immediately. I found this answer, but the issue is that run_server is blocking, so I can't join the net_thread after running the server.

I've thought about using an async coroutine to join the thread, but run_server already has an async loop so I've run into problems there.

How can I immediately raise an exception in the main thread as soon as the worker thread runs into one?

dirn
  • 19,454
  • 5
  • 69
  • 74
Jordan Sim
  • 67
  • 9
  • Why not just run two programs/processes? Is there anything happening in the background thread that's dependent on the blocking server call? Another option is to look for an async version of the run_server method. – sleepystar96 Jan 13 '22 at 03:25
  • What library are you using to run your server? – sleepystar96 Jan 13 '22 at 03:26
  • It's a WebRTC server (probably more accurately a client) based off [this example](https://github.com/aiortc/aiortc/blob/main/examples/videostream-cli/cli.py) from aiortc. I'm not confident enough in async programming to make it async. As it turns out, the run_net can't run on a thread anyway - it also uses signals which only works on the main thread, so using a separate process using subprocess looks like the way to go. Still not sure how I propogate an exception from one to the other. – Jordan Sim Jan 13 '22 at 04:35
  • There is no way of "throwing immediately" an exception in one thread from another thread. If you can modify `run_server`'s implementation you can use [the same answer](https://stackoverflow.com/a/31614591/17457042) you found using `join` with a timeout of `0`. If you can not modify `run_server`, your last option is to protect `run_net` with an all-encompassing `try` block and use signals. – azelcer Jan 13 '22 at 14:10

0 Answers0