Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple arguments in Python thread

The following code passes a list (varbinds) and it works fine.

t1 = threading.Thread(target = Main2_TrapToTxtDb, args = (varBinds,))

Now I need to pass another variable - vString along with this.

Please help with a simple code.

like image 266
Manoj Kumar M Avatar asked Nov 14 '16 03:11

Manoj Kumar M


People also ask

How do you pass multiple arguments to a thread in Python?

Therefore, you have to put a comma, so it is interpreted as a tuple: (argument, ) . Since this tuple is meant to contain the arguments you pass to the thread's function, just put all the arguments in the tuple, as I wrote in the answer: (arg1, arg2, arg3, arg4) .

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.

Can you pass arguments to a thread?

You can only pass a single argument to the function that you are calling in the new thread. Create a struct to hold both of the values and send the address of the struct. Save this answer.

Can you multi thread in Python?

To recap, threading in Python allows multiple threads to be created within a single process, but due to GIL, none of them will ever run at the exact same time. Threading is still a very good option when it comes to running multiple I/O bound tasks concurrently.


1 Answers

The args parameter is a tuple, and allows you to pass many arguments to the target.

t1 = threading.Thread(target=Main2_TrapToTxtDb, args=(varBinds, otherVariable))

This is documented here:

threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

This constructor should always be called with keyword arguments. Arguments are:

group should be None; reserved for future extension when a ThreadGroup class is implemented.

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

args is the argument tuple for the target invocation. Defaults to ().

kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

like image 160
Right leg Avatar answered Oct 09 '22 19:10

Right leg