繁体   English   中英

Discord.py 和多线程

[英]Discord.py and multithreading

我对编程有点陌生,所以这个问题对某些人来说可能很愚蠢或很容易......我有一个关于多线程的问题,正在寻找一些文档或链接以了解更多。

假设我有一个 Discord 机器人,它在被调用时执行一个功能。 (写了一个简单的sum作为例子)

@client.command()
async def example(ctx):

    # (lets assume the code here is to grab the user input value
    # from two messages and transform the messages into int variables called 
    # "first" and "second")


first = int(msg1.content)
second = int(msg2.content)


# Function to perform

    def sum():
        time.sleep(5) # added a sleep to simulate the "complex" formula performing calculations and a web request.

        result = number1 + number2
        return result


    # Thread formula

    def thread():
        with ThreadPoolExecutor(max_workers = 2) as executor:
            executor.submit(sum)

    thread()
        

    
    # Send the result 
    await ctx.author.send(f'Waited 5 seconds and this is the result {thread()}')


client.run(TOKEN)

在我看来,发生的事情是线程正在调用 sum 函数。 当然是错误的,因为结果我得到了“无”值。

任何人都可以向我指出一些关于如何实现多线程或多处理的有用资源或文档吗?

或者就如何处理这种情况给出一些建议。 \\

多处理是解决方案吗? 任务不是 CPU 密集型的,所以我认为多线程是要走的路。

目标是让机器人能够同时处理多个请求。 现在确实可以,但是当请求花费更多时间时,它会变慢,或者有时甚至不发送最后一条消息。 我在 Repl.it 上进行测试,它显示“内存不足”(或类似的东西。我假设它是因为 Replit 只提供 0.4 个 vCPU,所以没什么大不了的),这让我研究了多线程。

提前致谢!

sum()正在返回一个值,但您从错误的地方得到了答案。 顺便说一句,你不应该调用函数sum() ,因为它已经是一个内置的 Python 函数。 但那是另一回事。

executor.submit() returns a Future `。 当 sum() 完成时,future 将得到结果

你想写:

    def thread():
        with ThreadPoolExecutor(max_workers = 2) as executor:
            return executor.submit(sum)

    future = thread()
    return future.result()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM