Search code examples
pythonfunctionasynchronouspython-asynciodynamic-function

run functions in paralel Python


I have a stream and i have a function I want to run, when i receive the message on this stream

  async def some_func():
    asyncio.sleep(5)
    print("hello world")

  client = create_client('wax.dfuse.eosnation.io:9000')
  stream = client.Execute(Request(query = OPERATION_EOS))

  for rawRequest in stream:
    async.gather(some_func())

If there are 2 or more messages at the same time I want 2 or more functions that run in parallel.

Currently this script does not run a function

I need just a way to run function independently from main function.


Solution

  • Somehow I made it working.

    My code:

    async def some_func(rawResult):
      # There is some code
    
    async def stream_eosio(loop):
      for rawResult in stream:
        asyncio.run_coroutine_threadsafe(some_func(rawResult), loop)
    
    if __name__ == "__main__":
      loop = asyncio.new_event_loop()
      Thread(target=asyncio.run, args=(stream_eosio(loop),)).start()
      loop.run_forever()
    

    Cons: You can't stop this script with Ctrl + Z or Ctrl + C, because of Thread.

    Pros: It's kinda ez.