dateTime.strptime()正在阻止asyncio.queue.get()

问题描述 投票:0回答:1

在以下代码dateTime.strptime()中,正在阻止asyncio.queue.get()操作

import time
import asyncio
from datetime import datetime
from functools import partial

def write(queue):

    data = dict(fname = "Stack", lname = "Overflow")
    
    # If you comment the below line thing are working fine
    dob = datetime.strptime("2025-02-12", "%Y-%m-%d")

    queue.put_nowait(data)
    print("Writing to queue complete")
    time.sleep(3600)  # sleep forever

async def reader(queue):
    loop = asyncio.get_running_loop()
    print("This print means this thread is not blocked")
    while msg := await queue.get():
        print("Got my message", msg)
        loop.call_soon(print, msg)

async def main():
    queue = asyncio.Queue()
    loop = asyncio.get_running_loop()
    loop.run_in_executor(None, partial(write, queue))
    await reader(queue)

asyncio.run(main())

如果我评论dateTime.strptime()函数调用,我将获得以下输出

Writing to queue complete
This print means this thread is not blocked
Got my message {'fname': 'Stack', 'lname': 'Overflow'}
{'fname': 'Stack', 'lname': 'Overflow'}

但如果未评论dateTime.strptime(),我将获得以下输出

This print means this thread is not blocked
Writing to queue complete

为什么dateTime.strptime()阻止asyncio.queue.get()操作?

python-3.x python-asyncio python-datetime
1个回答
0
投票
这与

datetime.strptime

无关。从事件循环外部拨打
queue.put_nowait
是不安全的。 
docs特别提到 ASYNCIO队列不是线程安全

因此,您无法安全地从执行程序线程调用

queue.put_nowait
。执行所需的时间

datetime.strptime

简单地更改了执行时间,以使不安全的调用引起问题。
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.