【发布时间】:2016-10-23 15:12:36
【问题描述】:
之前,我使用了以下代码:
for (int i = 0; i < config.threads; i++)
{
Thread thread = new Thread(workThread);
thread.IsBackground = true;
thread.Start();
}
public static void workThread()
{
while (true)
{
// work, 10 second
}
}
它工作正常,但在 10-15 个周期后,开始工作较少。然后我写了一个类来创建单独的线程:
class ThreadsPool
{
private static int maxThreads = 0;
private static Thread[] threadsArray;
private static int activeThread = 0;
public static void Initializer(int maxThreads)
{
ThreadsPool.maxThreads = maxThreads;
for (int i = 0; i < maxThreads; i++)
{
Thread thread = new Thread(Program.workThread);
thread.IsBackground = true;
thread.Start();
}
Thread threadDaemon = new Thread(Daemon);
threadDaemon.IsBackground = true;
threadDaemon.Start();
}
public static void activeThreadMinus()
{
Interlocked.Decrement(ref activeThread);
}
private static void Daemon()
{
while(true)
{
if(activeThread < maxThreads)
{
Thread thread = new Thread(Program.workThread);
thread.IsBackground = true;
thread.Start();
}
Thread.Sleep(5);
}
}
public static void workThread()
{
while (true)
{
// work 10 sec
ThreadsPool.activeThreadMinus();
}
}
}
但问题是这个类会造成内存泄漏。 你是否意识到我必须做 10 秒的工作,几乎无限次,有时运行线程的数量会发生变化。如何在没有内存泄漏和性能损失的情况下做到这一点。
【问题讨论】:
-
起初你在做什么,你需要多达 200 个线程?我认为这是一个设计问题。如果你有 200 个线程在运行,你总是会遇到性能问题。没有任何 Prozessor 可以快速处理这个问题。
-
我需要处理图像。我知道线程 200 并非不可能。
-
不要闯入200个线程。分解成线程数等于CPU核心数。
-
可能你需要一个线程池来代替?
-
默认情况下,TPL (
Parallel.For) 和 PLINQ (enumerable.AsParallel()) 框架将使用适当数量的线程处理您的数据(我认为这是逻辑核心数 * 2)。
标签: c# multithreading