英文:
Threading/multiprocessing in replacement to dictionary in discord.py music bot
问题
我观看了一个视频,一个人使用字典在几个不同的 Discord 服务器上运行音乐机器人的代码看起来是这样的:
#.... __init__..... self.vc = {}
async def join_VC(self, ctx, channel):
id = int(ctx.guild.id)
if self.vc[id] == None or not self.vc[id].is_connected():
self.vc[id] = await channel.connect()
if self.vc[id] == None:
await ctx.send("无法连接到语音频道。")
return
else:
await self.vc[id].move_to(channel)
我的问题是:是否可以使用线程或多进程来替代字典?如果可以的话,你们推荐使用什么?
完整代码:https://github.com/TheRealDulanOoga/GeraldTheRobot/tree/6aeec689b9a533527abfea54298ae88a0bd4d691
我不知道是否应该在整个类上使用多进程(这可行吗?)还是只在几个函数上使用。我有点困惑,需要一些建议。
<details>
<summary>英文:</summary>
I watched a video where a man used dictionary to run a music bot on few different discord servers and the code looks like this:
#.... init..... self.vc = {}
async def join_VC(self, ctx, channel):
id = int(ctx.guild.id)
if self.vc[id] == None or not self.vc[id].is_connected():
self.vc[id] = await channel.connect()
if self.vc[id] == None:
await ctx.send("Could not connect to the vouce channel.")
return
else:
await self.vc[id].move_to(channel)
My question is: Is it possible to use threading or multiprocessing in replacement to dictionary? If yes then what do you guys reccomend?
full code: https://github.com/TheRealDulanOoga/GeraldTheRobot/tree/6aeec689b9a533527abfea54298ae88a0bd4d691
I don't know if I should use multiprocessing on whole class (is it possible?) or just on few functions. I'm a bit confused I need an advice.
</details>
# 答案1
**得分**: 0
你的函数已经是异步的,意味着它可以并行运行。因此,真的没有必要将其线程化...
线程化只是意味着你创建一个运行该函数的进程。
异步意味着这个函数不会阻塞代码。
你想要的结果只是不阻塞代码,当然你可以将函数线程化,但这样做没有任何好处。
<details>
<summary>英文:</summary>
your function is already async, means it can run parallel. So there is really no nead for threading it ...
threading simply means you create a process that runs the function
async means this function wont block the code
and the result you want is only to not block the code, of course can you thread the function but there would be no benefits by doing so
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论