我有一个处理大块信息的子例程。为了利用整个CPU,它将工作划分为单独的线程。所有线程完成后,结束。我读过创建和销毁线程使用大量开销,所以我尝试使用线程池,但实际上运行速度比创建自己的线程慢。如何在程序运行时创建自己的线程,然后继续重用它们?我见过一些人说它不能完成,但是线程池是这样做的,所以它一定是可能的,对吧?如何在.NET 3.5中重用线程
这里是启动新线程的部分代码/使用线程池:
//initialization for threads
Thread[] AltThread = null;
if (NumThreads > 1)
AltThread = new Thread[pub.NumThreads - 1];
do
{
if (NumThreads > 1)
{ //split the matrix up into NumThreads number of even-sized blocks and execute on separate threads
int ThreadWidth = DataWidth/NumThreads;
if (UseThreadPool) //use threadpool threads
{
for (int i = 0; i < NumThreads - 1; i++)
{
ThreadPool.QueueUserWorkItem(ComputePartialDataOnThread,
new object[] { AltEngine[i], ThreadWidth * (i + 1), ThreadWidth * (i + 2) });
}
//get number of threads available after queue
System.Threading.Thread.Sleep(0);
int StartThreads, empty, EndThreads;
ThreadPool.GetAvailableThreads(out StartThreads, out empty);
ComputePartialData(ThisEngine, 0, ThreadWidth);
//wait for all threads to finish
do
{
ThreadPool.GetAvailableThreads(out EndThreads, out empty);
System.Threading.Thread.Sleep(1);
} while (StartThreads - EndThreads > 0);
}
else //create new threads each time (can we reuse these?)
{
for (int i = 0; i < NumThreads - 1; i++)
{
AltThread[i] = new Thread(ComputePartialDataOnThread);
AltThread[i].Start(new object[] { AltEngine[i], ThreadWidth * (i + 1), ThreadWidth * (i + 2) });
}
ComputePartialData(ThisEngine, 0, ThreadWidth);
//wait for all threads to finish
foreach (Thread t in AltThread)
t.Join(1000);
foreach (Thread t in AltThread)
if (t.IsAlive) t.Abort();
}
}
}
ComputePartialDataOnThread只是解包的信息,并调用ComputePartialData。将被处理的数据在线程中共享(它们不会尝试读取/写入相同的位置)。 AltEngine []是每个线程的独立计算引擎。
该操作使用线程池运行约10-20%。
你可以发布你的代码,以便我们可以看到你在做什么?有可能你在线程池中做了一些错误,导致它很慢。 – 2011-04-29 01:42:06
也许它只在你的测试运行中很慢,也就是说你点击了最初的线程数,所以它必须创建更多的线程来满足你的需求。在运行任何测试之前,尝试手动设置池中的最小线程数。 – 2011-04-29 01:50:55
线程的数量意味着匹配处理器内核的数量。在这种情况下,它只有2. – HypnoToad 2011-04-29 02:07:29