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?
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().
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.
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.
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With