【发布时间】:2014-01-27 16:45:07
【问题描述】:
我想要达到的目标:
使用Parallel.For(其他任何东西都会受到赞赏,但发现这个是最简单的)我想增加一个名为max的变量,使其使用线程达到100,000,000,但程序应该同时只使用 X 个线程。
代码 sn-p:
using System;
using System.Threading;
using System.Linq;
using System.Threading.Tasks;
using System.Diagnostics;
namespace pool_threading
{
class MainClass
{
static int max=0;
static int current_max_thread=0;
public static void Main (string[] args)
{
Parallel.For(0, 100000000, new ParallelOptions { MaxDegreeOfParallelism = 50 },
i =>
{
max++;
if(Thread.CurrentThread.ManagedThreadId>current_max_thread)
current_max_thread=Thread.CurrentThread.ManagedThreadId;
});
Console.WriteLine ("I got to this number {0} using most {1} threads",max,current_max_tread);
}
public static void GetPage(int i)
{
}
}
}
结果:
我使用最多 11 个线程得到了这个号码 38,786,886
现在......我不知道为什么我得到的数字 38,786,886 小于 38,786,886,但我想这是因为多个线程试图同时增加它,所以如果 10同时尝试,只有第一个才有机会。如果我错了,请纠正我。
最大的“问题”是我一直有 11 个线程,即使最大值设置为 50(滚动代码查看最大值),如果我将其设置为最大 1 个线程,我总是得到 4 个(也许在这种情况下,4 是最小值,但它仍然不能解释为什么我同时得到的最大值只有 11)。
【问题讨论】:
-
为什么你需要精确的
X线程数?
标签: c# multithreading parallel-processing parallel.foreach