解决阻止http python函数通过Asyncio

时间:2017-12-09 17:27:29

标签: python python-asyncio

我正在实施一个通过http请求(inspired by this blogpost)进行通信的区块链。这个区块链有一个工作证明方法,根据难度,可以在很长一段时间内阻止其他http请求。这就是我尝试从python实现新的$(function() { })功能的原因。以下作品:

asyncio

然而,这使得我的工作证明非常缓慢,我想这是因为它在每次迭代后被迫睡眠。什么是更优雅的方法来解决这个问题?

async def proof_of_work(self, last_proof):
    """
    Simple Proof of Work Algorithm:
     - Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p'
    """
    proof = 0
    while self.valid_proof(last_proof, proof) is False:
        proof += 1
        await asyncio.sleep(1)

    return proof

会加快一点,但看起来有点脏。实现这个的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

如果你想在coroutine中运行CPU阻塞代码,你应该使用run_in_executor()在单独的执行流程中运行它(以避免asyncio的事件循环冻结)。

如果您只想要其他执行流程,或者(我认为更好)使用ThreadPoolExecutor将CPU相关工作委托给其他核心,您可以使用ProcessPoolExecutor

import asyncio
from concurrent.futures import ProcessPoolExecutor
import hashlib


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


def proof_of_work(last_proof):
    proof = 0
    while valid_proof(last_proof, proof) is False:
        proof += 1
    return proof


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


async def main():
    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()

<强>输出:

69732