首页 > 解决方案 > Discord.py 和多线程

问题描述

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

假设我有一个 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,所以没什么大不了的),这让我研究了多线程。

提前致谢!

标签: pythonmultithreadingdiscordmultiprocessing

解决方案


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

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

你想写:

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

    future = thread()
    return future.result()

推荐阅读