Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thread with multiple parameters

Does anyone know how to pass multiple parameters into a Thread.Start routine?

I thought of extending the class, but the C# Thread class is sealed.

Here is what I think the code would look like:

...     Thread standardTCPServerThread = new Thread(startSocketServerAsThread);      standardServerThread.Start( orchestrator, initializeMemberBalance, arg, 60000); ... }  static void startSocketServerAsThread(ServiceOrchestrator orchestrator, List<int> memberBalances, string arg, int port) {   startSocketServer(orchestrator, memberBalances, arg, port); } 

BTW, I start a number of threads with different orchestrators, balances and ports. Please consider thread safety also.

like image 473
Lucas B Avatar asked May 06 '09 18:05

Lucas B


People also ask

How do you pass multiple arguments in a thread?

if you declare parameter to be an array of int ("int parameter[2];"), then you can pass parameter as a pointer. It is the pointer to first int. You can then access it from the thread as an array.

How do you pass multiple parameters 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) .

What is a thread parameter?

Describes the effect of the threads parameter in parallel. You manage the number of threads that CPLEX uses with the global thread count parameter ( Threads , CPX_PARAM_THREADS ) documented in the CPLEX Parameters Reference Manual.

How do you pass a variable from one thread to another in Java?

When you create a new thread, you pass in the parameter in the function call. So if you want to pass an integer, you would pass in the variable, typically in the void* parameter, of the create thread method.


2 Answers

Try using a lambda expression to capture the arguments.

Thread standardTCPServerThread =    new Thread(     unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)   ); 
like image 70
JaredPar Avatar answered Sep 30 '22 03:09

JaredPar


Here is a bit of code that uses the object array approach mentioned here a couple times.

    ...     string p1 = "Yada yada.";     long p2 = 4715821396025;     int p3 = 4096;     object args = new object[3] { p1, p2, p3 };     Thread b1 = new Thread(new ParameterizedThreadStart(worker));     b1.Start(args);     ...     private void worker(object args)     {       Array argArray = new object[3];       argArray = (Array)args;       string p1 = (string)argArray.GetValue(0);       long p2 = (long)argArray.GetValue(1);       int p3 = (int)argArray.GetValue(2);       ...     }> 
like image 21
Opus Avatar answered Sep 30 '22 04:09

Opus