gpt4 book ai didi

c# - 多线程时的意外结果

转载 作者:行者123 更新时间:2023-11-30 15:58:00 25 4
gpt4 key购买 nike

<分区>

我有一个函数,该函数将由使用开始和结束参数启动的线程调用。该函数在单个主线程上运行时运行良好。但是,当我尝试对其进行多线程处理时,代码中断了。

函数如下:

static void processThread(long startLimit, long endLimit)
{
long rangeLimit = startLimit;
while (startLimit < endLimit) {
rangeLimit = rangeLimit + 100;
startLimit++;
Console.WriteLine("Processed for " + startLimit + ", " + rangeLimit);
startLimit = rangeLimit;
}
}

我从 main as::中调用它

int threadCount = 4;
long[] startPoints = new long[threadCount];
long[] endPoints = new long[threadCount];
if ((endLimit / 100) % threadCount == 0)
{
for (int i = 0; i < threadCount; i++)
{
endPoints[i] = endLimit * (i + 1) / threadCount;
}
startPoints[0] = 0;
for (int i = 1; i < threadCount; i++)
{
startPoints[i] = endPoints[i - 1];
}
}
Thread[] threads = new Thread[threadCount];
for (int i = 0; i < threadCount; i++)
{
threads[i] = new Thread(() => processThread(startPoints[i], endPoints[i]));
threads[i].Start();
Console.WriteLine("Started for " + startPoints[i] + ", " + endPoints[i]);
}

预期的结果是这样的

Processed for 1, 100
Processed for 101, 200
Processed for 201, 300
Processed for 301, 400
Processed for 401, 500
Processed for 501, 600
Processed for 601, 700
Processed for 701, 800
.....

等等......但我得到的是:

Started for 0, 2500
Started for 2500, 5000
Processed for 5001, 5100
Processed for 5101, 5200
Processed for 5201, 5300
Processed for 5301, 5400
Processed for 5401, 5500
Processed for 5501, 5600
Processed for 5601, 5700
Processed for 5001, 5100
Started for 5000, 7500
Processed for 5001, 5100
Processed for 5101, 5200
Processed for 5201, 5300
Processed for 5301, 5400
Processed for 5401, 5500
Processed for 5501, 5600
Processed for 5601, 5700
Processed for 5701, 5800
Processed for 5801, 5900
Processed for 5901, 6000
Processed for 6001, 6100
Processed for 6101, 6200
Started for 7500, 10000
Processed for 6201, 6300
Processed for 6301, 6400
Processed for 6401, 6500
Processed for 6501, 6600
Processed for 5701, 5800

它有很多重复值,并且没有 0-2500 范围内的值。我也尝试了 Task.Factory,并得到了相同的结果。

如有任何帮助,我们将不胜感激。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com