Skip to content Skip to sidebar Skip to footer

Solve Blocking Http Python Function Through Asyncio

I am implementing a blockchain that communicates through http requests (inspired by this blogpost). This blockchain has a proof of work method, that, depending on the difficulty, c

Solution 1:

If you want to run CPU-blocking code inside coroutine, you should run it in separate execution flow (to avoid asyncio's event loop freezing) using run_in_executor().

You can use ThreadPoolExecutor if you just want another execution flow or (I think better) to use ProcessPoolExecutor to delegate CPU related work to other core(s).

import asyncio
from concurrent.futures import ProcessPoolExecutor
import hashlib


# ORIGINAL VERSION:# https://github.com/dvf/blockchain/blob/master/blockchain.pydefvalid_proof(last_proof, proof):
    guess = f'{last_proof}{proof}'.encode()
    guess_hash = hashlib.sha256(guess).hexdigest()
    return guess_hash[:4] == "0000"defproof_of_work(last_proof):
    proof = 0while valid_proof(last_proof, proof) isFalse:
        proof += 1return proof


# ASYNC VERSION:asyncdefasync_proof_of_work(last_proof):
    proof = await loop.run_in_executor(_executor, proof_of_work, last_proof)
    return proof


asyncdefmain():
    proof = await async_proof_of_work(0)
    print(proof)


if __name__ ==  '__main__':
    _executor = ProcessPoolExecutor(4)

    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(main())
    finally:
        loop.run_until_complete(loop.shutdown_asyncgens())
        loop.close()

Output:

69732

Post a Comment for "Solve Blocking Http Python Function Through Asyncio"