Variable Passed To Multiple Threads Of The Same Function
Solution 1:
How do you get 'embed'? Notice that 'embed' and 'tag' are always passed to every newly created thread, you need to do a deepcopy of each if necessary
from copy import deepcopy
for hook in webhooks:
thread.start_new_thread(send_hook,(hook, deepcopy(embed), tag))
Solution 2:
You are experiencing a race condition. Two threads have access to the same variable, and they are both modifying the variable. The outcome of your program depends on which one reaches the code that changes the variable first.
There are two possible solutions, depending on how you want the problem to be resolved:
If you don't need all threads to share the same value, or if the object is small and cheap to copy, make a copy of the variable you are passing before you pass it, by passing
deepcopy(embed)
instead ofembed
- see the solution posted by @user1438644 for code.If you want all threads to share the same value, or if it is expensive to make copies of the object, you will need to create a lock with
my_lock = threading.Lock()
, and when you get to the race condition part of your program (i.e., the part that modifies the shared variable), surround it with a context managerwith my_lock:
, which acquires the lock at the start and returns the lock when finished. For example:
import threading
my_lock = threading.Lock()
# your code herefor hook in webhooks:
threading.Thread(send_hook, args=(hook, embed, tag))
# more code heredefsend_hook(hook, embed, tag):
# Ensure embed is only changed by one thread at a timewith my_lock:
print("Lock acquired")
embed.set_footer(text="hello world")
webhook = Webhook(hook[1])
webhook.send(embed=embed)
Post a Comment for "Variable Passed To Multiple Threads Of The Same Function"