Thread with Multiple Parameters

thread with multiple parameters

Try using a lambda expression to capture the arguments.

Thread standardTCPServerThread = 
new Thread(
unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)
);

How to create a thread with multiple parameters?

You can make it super easy by just doing this:

Thread wms = new Thread(() => appUpdater("WMS", "StuMenu"));
wms.Start();

Alternatively, use a Task - tasks are more modern and you'll find built in language support for doing clever things with them. Don't learn threads, learn tasks.

Task t = Task.Run(() => appUpdater("WMS", "StuMenu"));

create new Thread, passing two parameters

You can't do it that way. The Thread.Start() method doesn't include overloads supporting more than one parameter.

However, the general goal is easily solved using an anonymous method as your thread body:

static void Main()
{
int x=10;
int y=100;
// in this line appear error
Thread t=new Thread(() => Add(x, y));
t.start();
}

I.e. instead of your Add() method being the thread entry point, you wrap it in an anonymous method (declared here via the lambda expression syntax). The arguments x and y are "captured" by the anonymous method, to be passed into the Add() method when the thread starts.

One very important caution: the values from the variables are only retrieved when the Add() method is actually called. That is when the thread starts. If you modify their values before that happens, the new values are what are used.

This idiom is usable in any context where you want to pass strongly-typed and/or multiple arguments to a method where normally the API would allow none or some fixed number (like just one). Event handlers, Task entry points, I/O callbacks, etc. all can benefit from this approach.

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

python threading - multiple parameter and return

In my opinion, you should besides this thread run another thread that checks if there is result. Or Implement callback that is called at the end of the thread. However, since you have gui, which as far as I know is simply a class -> you can store result into obj/class variable and check if the result came.

I would use mutable variable, which is sometimes used. Lets create special class which will be used for storing results from thread functions.

import threading
import time
class ResultContainer:
results = [] # Mutable - anything inside this list will be accesable anywher in your program

# Lets use decorator with argument
# This way it wont break your function
def save_result(cls):
def decorator(func):
def wrapper(*args,**kwargs):
# get result from the function
func_result = func(*args,**kwargs)

# Pass the result into mutable list in our ResultContainer class
cls.results.append(func_result)

# Return result from the function
return func_result

return wrapper

return decorator

# as argument to decorator, add the class with mutable list
@save_result(ResultContainer)
def func(a,b):
time.sleep(3)
return a,b

th = threading.Thread(target=func,args=(1,2))
th.daemon = True
th.start()

while not ResultContainer.results:
time.sleep(1)
print(ResultContainer.results)

So, in this code, we have class ResultContainer with list. Whatever you put in it, you can easily access it from anywhere in the code (between threads and etc... exception is between processes due to GIL). I made decorator, so you can store result from any function without violating the function. This is just example how you can run threads and leave it to store result itself without you taking care of it. All you have to do, is to check, if the result arrived.

You can use global variables, to do the same thing. But I dont advise you to use them. They are ugly and you have to be very careful when using them.


For even more simplicity, if you dont mind violating your function, you can just, without using decorator, just push result to class with list directly in the function, like this:

def func(a,b):
time.sleep(3)
ResultContainer.results.append(tuple(a,b))
return a,b

How to pass multiple parameters to a thread in C

Since you pass in a void pointer, it can point to anything, including a structure, as per the following example:

typedef struct s_xyzzy {
int num;
char name[20];
float secret;
} xyzzy;

xyzzy plugh;
plugh.num = 42;
strcpy (plugh.name, "paxdiablo");
plugh.secret = 3.141592653589;

status = pthread_create (&server_thread, NULL, disk_access, &plugh);
// pthread_join down here somewhere to ensure plugh
// stay in scope while server_thread is using it.

Passing multiple arguments in Python thread

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 {}.

Store a thread with multiple parameters - WPF

You can encapsulate the parameters in a class, but you can encapsulate also your logic in the class:

public class FooProcessor
{
private readonly Color _color1;
private readonly Color _color2;

public FooProcessor(Color color1, Color color2)
{
_color1 = color1;
_color2 = color2;
}

public Task ProcessAsync()
{
return Task.Run((Action) Process);
}

private void Process()
{
//add your logic here
}
}

OT: if you don't have specific reason to use Thread instead of Task, use Task. Some older tutorials use Threads, because Task didn't exist at that time.

C++/CLR Passing multiple arguments in threads

Like in any other situation where you have to put multiple values into one object, you either:

  • create a wrapper class or struct (the clean way)
  • or use some predefined one like Tuple (the lazy way)

Here's the lazy way:

void Animal::Hungry(Object^ param)
{
auto args = safe_cast<Tuple<String^, int>^>(param);
Console::WriteLine("The animal eats {1} {0}", args->Item1, args->Item2);
}

void main()
{
Animal^ test = gcnew Animal;
Thread^ threads = gcnew Thread(gcnew ParameterizedThreadStart(test, &Animal::Hungry));
threads->Start(Tuple::Create("Grass", 1));
}


Related Topics



Leave a reply



Submit