我对编程有点陌生,所以这个问题对一些人来说可能很愚蠢或容易…我有一个关于多线程的问题,并寻找一些文档或链接来更多地了解它。
让我们假设我有一个在调用时执行功能的Discord bot。(写一个简单的和作为例子)
@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函数。当然是错的因为我得到的是" none "值作为结果。
谁能指出我一些有用的资源或文档如何实现多线程或多处理?
或者给出一些如何处理这种情况的建议。
多进程是解决方案吗?这个任务不是CPU密集型的,所以我认为多线程是可行的。
目标是让bot能够同时处理多个请求。现在是这样的,但是当请求多一点时,它就会变慢,有时甚至不发送最后的消息。我在测试Repl。它显示出"低内存"。(或者类似的东西。我认为这是因为Replit只提供0.4 vCPU,所以没什么大不了的),这让我研究了多线程。
提前感谢!
sum()
返回一个值,但是你从错误的地方获得答案。顺便说一下,你不应该调用函数sum()
,因为它已经是一个内置的Python函数了。但那是另一回事。
executor.submit() returns a
Future '。该future将在sum()完成时获得结果
你想写:
def thread():
with ThreadPoolExecutor(max_workers = 2) as executor:
return executor.submit(sum)
future = thread()
return future.result()