我正在实现一个通过http请求(inspired by this blogpost)进行通信的区块链。这个区块链有一个工作证明方法,根据难度,可以在相当长的时间内阻止其他http请求。这就是为什么我试图从python实现新的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
然而,这使得我的工作证明非常缓慢,我想这是因为它在每次迭代之后都被迫休眠。有什么更优雅的方法来解决这个问题呢?在
^{pr2}$会加快一点,但看起来有点脏。正确的实施方法是什么?在
如果您想在协同程序中运行CPU阻塞代码,应该使用
run_in_executor()
在单独的执行流中运行它(以避免异步的事件循环冻结)。在如果您只想使用另一个执行流,或者(我认为更好)使用
ThreadPoolExecutor
将与CPU相关的工作委托给其他核心。在输出:
^{pr2}$相关问题 更多 >
编程相关推荐