在编写把一个30万条数据批量轮询调用拆分为多个线程(每个线程运行一部分数据)轮询调用时,发现多个线程和单次执行的时间没有太大差别
此时用系统自带的性能监视器发现,拆分成多个线程后占用的cpu和拆分前差不多,为此排查代码中的各模块处理逻辑发现了此类问题
尽量减少线程间同时使用到的公共变量,当把所有公共变量都变为线程内变量时发现多线程的运算优势明显体现处理
试例代码:
public class MutiThread
{
public void
TestSerial()
{
//Console.WriteLine(AppDomain.GetCurrentThreadId());
Stopwatch sw
= new Stopwatch();
sw.Start();
TestRun(100000);
sw.Stop();
Console.WriteLine("单条:" + sw.ElapsedMilliseconds);
}
//private int Cur = 0;
public void TestRun(object
objState)
{
int Count = (int)objState;
for (int i = 0; i < Count; i++)
{
int Cur = 0;
for (int j = 0; j <
10000; j++)
{
Cur +=
j;
}
//Thread.Sleep(1);
}
}
public void ThreadTestRun(object objState)
{
MutiState state = objState as MutiState;
//Console.WriteLine(AppDomain.GetCurrentThreadId());
TestRun(state.intCount);
state.resetEvent.Set();
}
public void TestParallel()
{
//Console.WriteLine(AppDomain.GetCurrentThreadId());
Stopwatch
sw = new Stopwatch();
sw.Start();
List<MutiState> listState = new List<MutiState>();
for (int i = 0; i < 10; i++)
{
MutiState
state = new MutiState(10000);
Thread th = new Thread(new
ParameterizedThreadStart(ThreadTestRun));
th.Start(state);
listState.Add(state);
}
WaitHandle.WaitAll(listState.Select(p =>
p.resetEvent).ToArray());
sw.Stop();
Console.WriteLine("多线程:" + sw.ElapsedMilliseconds);
}
}
public class MutiState
{
public int intCount { get;
set; }
public AutoResetEvent resetEvent { get; set; }
public MutiState(int intCur)
{
intCount =
intCur;
resetEvent = new AutoResetEvent(false);
}
}