Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array of threads c#

i have this code:

    Thread[] threadsArray = new Thread[4];
        for (int i = 0; i < 4; i++)
        {
            threadsArray[i] = new Thread(() => c1.k(i));
        }
        for (int i = 0; i < 4; i++)
        {
            threadsArray[i].Start();
        }
        for (int i = 0; i < 4; i++)
        {
            threadsArray[i].Join();
        }

the function k is this:

void k(int i)
{
    while(true)
      Console.WriteLine(i);
}

for some reason just the last thread is running and printing 4444444.... why aren't all the threads running?

like image 627
aharon Avatar asked Jul 19 '10 20:07

aharon


People also ask

Can we create array of threads?

You can create the array of threads (or list of threads, even) anywhere outside the for loop. Yes, collect them in an array. Or use an ExecutorService and awaitTermination().

What is pthread_create in C?

DESCRIPTION. The pthread_create() function is used to create a new thread, with attributes specified by attr, within a process. If attr is NULL, the default attributes are used. If the attributes specified by attr are modified later, the thread's attributes are not affected.

Does C have thread?

Each part of such a program is called a thread, and each thread defines a separate path of execution. C does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature.

How does pthread_ join work?

The pthread_join() function suspends execution of the calling thread until the target thread terminates, unless the target thread has already terminated. If status is non-NULL, the value passed to pthread_exit() by the terminated thread is stored in the location pointed to by status.


1 Answers

All of the threads are printing the same variable.

Your lambda expression (() => c1.k(i)) captures the i variable by reference.
Therefore, when the lambda expression runs after i++, it picks up the new value of i.

To fix this, you need to declare a separate variable inside the loop so that each lambda gets its own variable, like this:

    for (int i = 0; i < 4; i++)
    {
        int localNum = i;
        threadsArray[i] = new Thread(() => c1.k(localNum));
    }
like image 132
SLaks Avatar answered Nov 15 '22 22:11

SLaks