首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从python中的异步方法创建新线程的最佳方法

从python中的异步方法创建新线程的最佳方法
EN

Stack Overflow用户
提问于 2022-09-23 23:00:01
回答 1查看 93关注 0票数 0

我目前正在编写一个不和谐的机器人,它需要能够运行一个任务,这个任务可能需要几秒钟到一分钟的时间,同时还能响应其他命令。如果这是一个相当简单的问题,请原谅我,但我还没有找到一个有效的解决方案。

下面是代码的简略版本

代码语言:javascript
复制
class StableCog(commands.Cog, name='Stable Diffusion', description='Create images from natural language.'):
def __init__(self, bot):
    self.text2image_model = Text2Image()
    self.bot = bot

@commands.slash_command(description='Create an image.')
async def dream(self, -- a ton of arguments -- ):
    print(f'Request -- {ctx.author.name}#{ctx.author.discriminator} -- Prompt: {query}')
    asyncio.get_event_loop().create_task(src.bot.queue_system.dream_async( -- a ton of arguments -- ))

内部queue_system.py

代码语言:javascript
复制
async def dream_async(-- a ton of arguments --):
await ctx.interaction.response.send_message('Added to queue! You are # in queue')
embed = discord.Embed()
try:
    #lots of code, I've removed it since it doesn't have anything to do with the async
    await ctx.channel.send(embed=embed, file=discord.File(fp=buffer, filename=f'{seed}.png'))

except Exception as e:
    embed = discord.Embed(title='txt2img failed', description=f'{e}\n{traceback.print_exc()}', color=embed_color)
    await ctx.channel.send(embed=embed)

但是,在queue_system.py中的代码完成运行之前,不和谐的bot会变得没有响应性。到目前为止,我尝试过的每个解决方案都没有正确工作,因为我试图创建一个线程来运行异步方法。这样做最好的方法是什么?忽略名称queue_system.py,它还不是一个完全的队列系统,我只是在研究如何在计算出这个方法之前异步运行这个梦想的方法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-30 02:40:54

是什么阻塞了dream_async协同线中的事件循环?在该协同机制中,如果您调用一些可能阻塞循环的(非异步)函数,这是一个问题,但真正的罪魁祸首必须在“大量代码”部分:)

一个很好的选择是使用遗嘱执行人()在线程池中运行非异步代码,从而防止该代码阻塞dream_async。

代码语言:javascript
复制
def blocking_stuff(arg):
    # this will run in a thread
    ...
    
    return 'something'


async def dream_async(-- a ton of arguments --):
    loop = asyncio.get_event_loop()

    await ctx.interaction.response.send_message('Added to queue! You are # in queue')
    embed = discord.Embed()

    try:
        # Run the blocking part in a threadpool
        result = await loop.run_in_executor(None, blocking_stuff, 'test') 

        await ctx.channel.send(embed=embed, file=discord.File(fp=buffer, filename=f'{seed}.png'))

    except Exception as e:
        embed = discord.Embed(title='txt2img failed', description=f'{e}\n{traceback.print_exc()}', color=embed_color)
        await ctx.channel.send(embed=embed)

希望我没有误解你。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73833686

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档