Python 传递给同一函数的多个线程的变量
我目前正在开发一个系统,使用dhooks将webhook发送到多个Discord 这是用于调用发送Webhook的函数的函数。Python 传递给同一函数的多个线程的变量,python,webhooks,python-multithreading,Python,Webhooks,Python Multithreading,我目前正在开发一个系统,使用dhooks将webhook发送到多个Discord 这是用于调用发送Webhook的函数的函数。webhooks的长度是2,它是一个列表列表 for hook in webhooks: thread.start_new_thread(send_hook,(hook, embed, tag)) 这是send_hook函数: def send_hook(hook, embed, tag): embed.set_footer(text="{} x Wi
webhooks
的长度是2,它是一个列表列表
for hook in webhooks:
thread.start_new_thread(send_hook,(hook, embed, tag))
这是send_hook函数:
def send_hook(hook, embed, tag):
embed.set_footer(text="{} x Will".format(hook[0])) <-- This is the part where the error happens
webhook = Webhook(hook[1])
webhook.send(embed=embed)
我感谢所有的帮助
谢谢您如何获得“嵌入”?请注意,“嵌入”和“标记”总是传递给每个新创建的线程,如果需要,您需要对每个线程进行深度复制
from copy import deepcopy
for hook in webhooks:
thread.start_new_thread(send_hook,(hook, deepcopy(embed), tag))
你正在经历一场灾难。两个线程可以访问同一个变量,并且都在修改该变量。程序的结果取决于哪个程序首先到达更改变量的代码
根据您希望如何解决问题,有两种可能的解决方案:
deepcopy(embed)
,而不是embed
——请参阅获取代码my_lock=threading.lock()
创建一个锁,当您到达程序的竞争条件部分(即修改共享变量的部分)时,用带有my_lock:的上下文管理器包围它,它在开始时获取锁,在完成时返回锁。例如:
导入线程
my_lock=threading.lock()
#你的代码在这里
对于webhooks中的钩子:
threading.Thread(send_hook,args=(hook,embed,tag))
#这里有更多代码
def发送挂钩(挂钩、嵌入、标记):
#确保一次只更改一个线程的嵌入
用我的锁:
打印(“已获取锁”)
嵌入.设置页脚(text=“hello world”)
webhook=webhook(hook[1])
webhook.send(嵌入=嵌入)
嘿!因此,当发送到send_hook函数的每个线程时,embed是相同的,但是embed在send_hook函数中更改,并且对于每个线程,其更改为的值是不同的。如果您只是修改webhook的端点以发送一次webhook,然后您将丢弃您创建的webhook对象并结束线程,这个解决方案应该对你有用。我已经尝试了第一个选项,但是没有解决问题。是否有线程库的锁
您是否有正在使用的线程
python模块的链接?可能有一个acquire\u lock()
函数或类似的函数。您可以尝试dir(thread)
(如果thread
是您正在使用的模块的名称)。
from copy import deepcopy
for hook in webhooks:
thread.start_new_thread(send_hook,(hook, deepcopy(embed), tag))