When Do You Need to Pass Arguments to 'Thread.New'

When do you need to pass arguments to `Thread.new`?

When you pass a variable into a thread like that, then the thread makes a local copy of the variable and uses it, so modifications to it do not affect the variable outside of the thread you passed in

a = "foo"
Thread.new{ a = "new"}
p a # => "new"
Thread.new(a){|d| d = "old"}
p a # => "new"
p d # => undefined

Passing arguments to threading.Thread

args is a sequence of arguments to pass; if you want to pass in a list as the sole positional argument, you need to pass args=(my_list,) to make it a one-tuple containing the list (or mostly equivalently, args=[my_list]).

It needs to be a sequence of arguments, even when only one argument is passed, precisely to avoid the ambiguity you created. If scr_runner took three arguments, two with default values, and my_list had a length of 3, did you mean to pass the three elements as the three arguments, or should my_list be the first argument, and the other two remain the default?

create thread - passing arguments

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.

#include <pthread.h>
#include <stdlib.h>
typedef struct {
//Or whatever information that you need
int *max_prime;
int *ith_prime;
} compute_prime_struct;

void *compute_prime (void *args) {
compute_prime_struct *actual_args = args;
//...
free(actual_args);
return 0;
}
#define num_threads 10
int main() {
int max_prime = 0;
int primeArray[num_threads];
pthread_t primes[num_threads];
for (int i = 0; i < num_threads; ++i) {
compute_prime_struct *args = malloc(sizeof *args);
args->max_prime = &max_prime;
args->ith_prime = &primeArray[i];
if(pthread_create(&primes[i], NULL, compute_prime, args)) {
free(args);
//goto error_handler;
}
}
return 0;
}

how to pass arguments to a class when initializing a thread?

You pass your arguments on the init function.

class App():
def __init__(self, iterr):

How can I pass a parameter to a Java Thread?

You need to pass the parameter in the constructor to the Runnable object:

public class MyRunnable implements Runnable {

public MyRunnable(Object parameter) {
// store parameter for later user
}

public void run() {
}
}

and invoke it thus:

Runnable r = new MyRunnable(param_value);
new Thread(r).start();

How to pass arguments to thread functions in Python

Pardon; reflexive habit there. The threading library in particular provides a direct solution for you, so the workaround below the line is not necessary.

See the Thread documentation:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, \*, daemon=None)

[ ... ]

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

So we can just provide the args as appropriate:

# Note the comma in `('High',)`; we want a 1-element tuple.
sound = Thread(target=generate_sound, args=('High',))


But here I am not sure how do I pass the values High and Low to generate sound function.

This doesn't depend on understanding threading; it's a general technique for these kinds of "callback" functions (any time that you pass a function as a parameter to something else, basically). For example, frequently you need this technique for buttons when making a GUI with tkinter (or other toolkits).

Bind the parameter to the call, for example using functools.partial from the standard library:

from functools import partial
sound = Thread(target=partial(generate_sound, 'High'))

How to pass parameters to ThreadStart method in Thread?

The simplest is just

string filename = ...
Thread thread = new Thread(() => download(filename));
thread.Start();

The advantage(s) of this (over ParameterizedThreadStart) is that you can pass multiple parameters, and you get compile-time checking without needing to cast from object all the time.

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,)) # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved]) # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__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.

Difference of passing argument to std::thread, C++

t1:

This simply passes a copy of V to the thread.

t2:

Similarly to t1, a copy of V is passed to the thread, but the actual copy is made in the called thread instead of the caller thread. This is an important distinction because should V be altered or cease to exist by the time the thread begins, you will end up with either a different vector or Undefined Behavior.

t3:

This should fail to compile as the thread will move the vector into the LValue reference, which is supposed to be illegal.

t4:

This passes the vector by reference to the thread. Any modifications to the passed reference will be applied to V, provided that proper synchronisation is performed, of course.



Related Topics



Leave a reply



Submit