In this example, is this the correct use of the Parallel.For
loop if I want to limit the number of threads that can perform the function DoWork
to ten at a time? Will other threads be blocked until one of the ten threads becomes available? If not, what is a better multi-threaded solution that would still let me execute that function 6000+ times?
class Program
{
static void Main(string[] args)
{
ThreadExample ex = new ThreadExample();
}
}
public class ThreadExample
{
int limit = 6411;
public ThreadExample()
{
Console.WriteLine("Starting threads...");
int temp = 0;
Parallel.For(temp, limit, new ParallelOptions { MaxDegreeOfParallelism = 10 }, i =>
{
DoWork(temp);
temp++;
});
}
public void DoWork(int info)
{
//Thread.Sleep(50); //doing some work here.
int num = info * 5;
Console.WriteLine("Thread: {0} Result: {1}", info.ToString(), num.ToString());
}
}
The Parallel. For loop is just like the for loop except it allows the iterations to run in parallel across multiple threads. The Parallel. ForEach method splits the work to be done into multiple tasks, one for each item in the collection.
Can any for loop be made parallel? No, not any loop can be made parallel. Iterations of the loop must be independent from each other. That is, one cpu core should be able to run one iteration without any side effects to another cpu core running a different iteration.
Parallel programming is the process of using a set of resources to solve a problem in less time by dividing the work. Using parallel programming in C is important to increase the performance of the software.
The general way to parallelize any operation is to take a particular function that should be run multiple times and make it run parallelly in different processors. To do this, you initialize a Pool with n number of processors and pass the function you want to parallelize to one of Pool s parallization methods.
You need to use the i
passed to the lambda function as index. Parallel.For
relieves you from the hassle of working with the loop counter, but you need to use it!
Parallel.For(0, limit, new ParallelOptions { MaxDegreeOfParallelism = 10 }, i =>
{
DoWork(i);
});
As for your other questions:
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