您的位置:首页 > 大数据 > 云计算

云计算之路-阿里云上:消灭“黑色n秒”第一招——不让CPU空闲

2014-05-19 17:18 471 查看
class DistributedThread
{
[DllImport("kernel32.dll")]
public static extern int GetCurrentThreadId();

[DllImport("kernel32.dll")]
public static extern int GetCurrentProcessorNumber();

private ThreadStart threadStart;

private ParameterizedThreadStart parameterizedThreadStart;

private Thread thread;

public int ProcessorAffinity { get; set; }

public Thread ManagedThread
{
get
{
return thread;
}
}

private DistributedThread()
{
thread = new Thread(DistributedThreadStart);
}

public DistributedThread(ThreadStart threadStart)
: this()
{
this.threadStart = threadStart;
}

public DistributedThread(ParameterizedThreadStart threadStart)
: this()
{
this.parameterizedThreadStart = threadStart;
}

public void Start()
{
if (this.threadStart == null) throw new InvalidOperationException();

thread.Start(null);
}

public void Start(object parameter)
{
if (this.parameterizedThreadStart == null) throw new InvalidOperationException();

thread.Start(parameter);
}

private void DistributedThreadStart(object parameter)
{
try
{
// fix to OS thread
Thread.BeginThreadAffinity();

// set affinity
if (ProcessorAffinity != 0)
{
CurrentThread.ProcessorAffinity = new IntPtr(ProcessorAffinity);
}

// call real thread
if (this.threadStart != null)
{
this.threadStart();
}
else if (this.parameterizedThreadStart != null)
{
this.parameterizedThreadStart(parameter);
}
else
{
throw new InvalidOperationException();
}
}
finally
{
// reset affinity
CurrentThread.ProcessorAffinity = new IntPtr(0xFFFF);
Thread.EndThreadAffinity();
}
}

private ProcessThread CurrentThread
{
get
{
int id = GetCurrentThreadId();
return
(from ProcessThread th in Process.GetCurrentProcess().Threads
where th.Id == id
select th).Single();
}
}
}


DistributedThread
接下来,出招——KeepAllCpuCoresAlive!



结果。。。这一招以失败告终!



(上图是“黑色1秒”发生时性能监视器监测到的ASP.NET Requests/Sec为0的情况)

失败又如何,就如同代码编译不通过一般不值一提。那为什么还要写博客出来呢?分享的就是过程!

接下来呢?准备第二招。。。

【参考资料】

Running .NET threads on selected processor cores

Threading in C#

Keep Alive the Machine - No Sleep
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐