在没有Parallel.for()的情况下在c#中实现for循环中的多线程



我对多线程比较陌生。我已经编写了一个for循环,用于打印从0到用户指定的整数的值。我现在想把它平行化,使每条线程打印5个数字。当我使用Parallel.For((时,它是有效的。但我似乎无法手动完成。这是代码。

using System;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static int no = 0;
static void Main(string[] args)
{
Console.WriteLine("Enter a number");
no = int.Parse(Console.ReadLine());
//Parallel.For(0, no, i =>
//Console.WriteLine(i)
//);
//Console.ReadLine();
int start = 0, end = 5, i = 0;
int not = no / 5;
if (no <= 5)
{
func(start, no);
}
else
{
int index = i;
Thread[] t = new Thread[not + 1];
while (index < not + 1)
{
if (end - start >= 5 && end <= no)
t[index] = new Thread(() => func(start, end));
else
t[index] = new Thread(() => func(start, no));
start = end;
end = end + 5;
i++;
t[index].Start();
}
Console.ReadLine();
}
}
static public void func(int start, int end)
{
for (int i = start; i < end; i++)
{
Console.Write(i+",");
}
}
}
}

假设用户输入值为21。然后它产生以下输出

15,16,17,15,16,17,18,19,18,19,25,26,27,28,29,25,26,27,28,29

然而,在t[index].start((之后使用thread.join((后,会产生以下输出。

5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24

我似乎无法理解发生了什么,也无法调试此代码,因为有许多线程同时运行。

提前感谢

请注意,像() => func(start, end)这样的lambda表达式绑定到变量start和end,并且在执行时将使用变量此时碰巧具有的值,而不是创建线程时具有的值。

您可以通过首先将当前值分配给循环中定义的变量并在Lambda中使用这些变量来避免这种情况,例如

if (end - start >= 5 && end <= no)
{
var localStart = start;
var localEnd = end;
t[index] = new Thread(() => func(localStart, localEnd));
}
else
{
var localStart = start;
var localEnd = no;
t[index] = new Thread(() => func(localStart, localEnd));
}

最新更新