0

I am trying to run two threads concurrently in order to: collect data and save this data periodically. I am using socket to collect the data and module asyncio in order to run in parallel this two functions.

This is the code:

# IMPORT LIBRARIES:
import socket
import asyncio
# DEFINITION FUNCTION:
async def restart_variable():
    print("executes restart_variable")
    while True:
        await asyncio.sleep(20)
        print("Should clean and save data")
        print("For the moment only clean")
        totaldata = ""


async def collect_data():
    print("executes collect data")
    totaldata = ""
    while True:
        data = sock.recv(1024)
        data = str(data, "utf-8")
        totaldata += data
        print(1, len(totaldata))
        print(2, data)

async def main():
    try:
        sock.connect((HOST, PORT))
        print("Connected")
    except Exception as e:
        print("Cannot connect to the server:", e)
    try:
        asyncio.gather(restart_variable(), collect_data())


    except KeyboardInterrupt:
        print("Manually interrupted")
        sock.close()
    except Exception as e:
        print(e)
        sock.close()

HOST = "HOST"
PORT = 2304
# MAIN EXECUTION:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
asyncio.run(main())

However, only collect data is working. restart_variable function is only executed one time. I dont understand why while True has no effect.

  • 3
    `collect_data` needs to await something. As written above, once it begins running, it never yields control back to the event loop. – dirn Jun 05 '20 at 12:23
  • Also, asyncio is not multi threaded, it won't automatically parallelize blocking calls. You need to use the appropriate asyncio primitives instead of the raw `socket` module. See e.g. [this example](https://stackoverflow.com/a/52570820/1600898). – user4815162342 Jun 05 '20 at 15:56
  • @dirn which do you think would be a good pattern to do what I am trying to do? I have the intuition that the problem is about the considered architecture is not correct. – Antonio Andrés Jun 08 '20 at 05:30
  • This seems to be reasonable. https://stackoverflow.com/questions/61867504/best-practice-to-collect-and-execute-in-a-bunch-in-python – Antonio Andrés Jun 08 '20 at 06:42

0 Answers0