Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass keyword arguments to target function in Python threading.Thread

I want to pass named arguments to the target function, while creating a Thread object.

Following is the code that I have written:

import threading  def f(x=None, y=None):     print x,y  t = threading.Thread(target=f, args=(x=1,y=2,)) t.start() 

I get a syntax error for "x=1", in Line 6. I want to know how I can pass keyword arguments to the target function.

like image 974
xennygrimmato Avatar asked Jun 18 '15 10:06

xennygrimmato


People also ask

How do you pass an argument to a thread in Python?

Example 1 - Thread Argument Passing long taskids[NUM_THREADS]; for(t=0; t<NUM_THREADS; t++) { taskids[t] = t; printf("Creating thread %ld\n", t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *) taskids[t]); ... } See the source code.

What is a threading Active_count () in Python?

In Python, the method threading. active_co unt() from the threading module is used to count the currently active or running threads.

What are the limitations of threading in Python?

In fact, a Python process cannot run threads in parallel but it can run them concurrently through context switching during I/O bound operations. This limitation is actually enforced by GIL. The Python Global Interpreter Lock (GIL) prevents threads within the same process to be executed at the same time.

What does the target argument to the constructor of thread represent in Python?

What does the target argument to the constructor of thread represent in Python? Thread class Constructor It is reserved for future extension. target : This is the callable object or task to be invoked by the run() method.


1 Answers

t = threading.Thread(target=f, kwargs={'x': 1,'y': 2}) 

this will pass a dictionary with the keyword arguments' names as keys and argument values as values in the dictionary. the other answer above won't work, because the "x" and "y" are undefined in that scope.

another example, this time with multiprocessing, passing both positional and keyword arguments:

the function used being:

def f(x, y, kw1=10, kw2='1'):     pass 

and then when called using multiprocessing:

p = multiprocessing.Process(target=f, args=('a1', 2,), kwargs={'kw1': 1, 'kw2': '2'}) 
like image 61
vladosaurus Avatar answered Sep 23 '22 11:09

vladosaurus