Say that I have a function that looks like:
def _thread_function(arg1, arg2=None, arg3=None): #Random code
Now I want to create a thread using that function, and giving it arg2 but not arg3. I'm trying to this as below:
#Note: in this code block I have already set a variable called arg1 and a variable called arg2 threading.Thread(target=self._thread_function, args=(arg1, arg2=arg2), name="thread_function").start()
The above code gives me a syntax error. How do I fix it so that I can pass an argument to the thread as arg2?
You can protect data variables shared between threads using a threading. Lock mutex lock, and you can share data between threads explicitly using queue. Queue.
Example 2 - Thread Argument Passing my_data = (struct thread_data *) threadarg; taskid = my_data->thread_id; sum = my_data->sum; hello_msg = my_data->message; ... } int main (int argc, char *argv[]) { ... thread_data_array[t]. thread_id = t; thread_data_array[t].
If a Python newcomer wanted to know about passing by ref/val, then the takeaway from this answer is: 1- You can use the reference that a function receives as its arguments, to modify the 'outside' value of a variable, as long as you don't reassign the parameter to refer to a new object.
__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.
Use the kwargs parameter:
threading.Thread(target=self._thread_function, args=(arg1,), kwargs={'arg2':arg2}, name='thread_function').start()
you can also use lambda to pass args
threading.Thread(target=lambda: self._thread_function(arg1, arg2=arg2, arg3=arg3)).start()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With