Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable by name to a Thread in Python?

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?

like image 566
Dylan Avatar asked Aug 01 '11 21:08

Dylan


People also ask

How do you pass a variable between threads in Python?

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.

How do you pass args to thread?

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].

How do you pass by reference in Python?

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.

What is args in threading thread?

__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.


2 Answers

Use the kwargs parameter:

threading.Thread(target=self._thread_function, args=(arg1,),                  kwargs={'arg2':arg2}, name='thread_function').start() 
like image 103
unutbu Avatar answered Oct 08 '22 14:10

unutbu


you can also use lambda to pass args

threading.Thread(target=lambda: self._thread_function(arg1, arg2=arg2, arg3=arg3)).start() 
like image 28
Ali80 Avatar answered Oct 08 '22 15:10

Ali80