Windows自身没有提供类似Linux cgroup的能力来限制进程或进程组的资源占用,进程CPU/IO/内存/网络等资源的控制只能由自己实现。目前已有第三方的实现,主要是限制进程CPU的占用,如文档 < 21 Best Ways to Limit the CPU Usage of a Process > 所描述的BES,Process Tamer等软件。自Windows 8及Server 2012开始Windows系统有提供以job为单位的CPU占用及内存上限设置,之前的版本则只能以进程或线程为单位进行限制。
进程CPU占用限制方案
即时轮询系统所有进程(线程)的CPU占用,当发现所设定进程有超标时强制暂停进程所有线程的执行,然后在适当的时机再恢复执行。其中所涉及技术点:
进程CPU占用查询 GetProcessTimes
BOOL GetProcessTimes(
[in] HANDLE hProcess,
[out] LPFILETIME lpCreationTime,
[out] LPFILETIME lpExitTime,
[out] LPFILETIME lpKernelTime,
[out] LPFILETIME lpUserTime
);
此函数可以获取进程从创建至当前的总运行时间及总的CPU时间,(KernelTime + UserTime) < 系统CPU数 * (当前时间 - CreationTime)
线程CPU占用查询 GetThreadTimes
BOOL GetThreadTimes(
[in] HANDLE hThread,
[out] LPFILETIME lpCreationTime,
[out] LPFILETIME lpExitTime,
[out] LPFILETIME lpKernelTime,
[out] LPFILETIME lpUserTime
);
QueryThreadCycleTime可以提供更精准的CPU时间数据,单位为CPU时钟周期
BOOL QueryThreadCycleTime(
[in] HANDLE ThreadHandle,
[out] PULONG64 CycleTime
);
线程暂停及恢复
Windows平台没有提供暂停整个进程的支持函数,只能以线程为单位来操作,即SuspendThread及ResumeThread:
DWORD SuspendThread(
[in] HANDLE hThread
);
DWORD ResumeThread(
[in] HANDLE hThread
);
CPU亲和性设置: SetProcessAffinityMask
BOOL SetProcessAffinityMask(
[in] HANDLE hProcess,
[in] DWORD_PTR dwProcessAffinityMask
);
此函数可以限定进程及其所有线程所能使用的CPU,故一定程序上亦限定了进程最大的系统CPU占用率。
DWORD_PTR SetThreadAffinityMask(
[in] HANDLE hThread,
[in] DWORD_PTR dwThreadAffinityMask
);
此函数可单独限制特定线程的CPU亲和性。
进程优先级设置: SetPriorityClass
优先级解决的是优先运行及退让CPU的问题,本质上并不能限定CPU占用,只是优先级高于当前任务的忙碌的时候,当前进程会主动退让CPU 线程优先级设置:SetThreadPriority
BOOL SetThreadPriority(
[in] HANDLE hThread,
[in] int nPriority
);
Job Objects
Windows系统提供了Job的概念用以管理多个进程,可以限制Job对象内所有进程及期线程的CPU核心占用、CPU占用及内存分配上限等,均通过SetInformationJobObject来实现,具体的CPU限制由JOBOBJECT_CPU_RATE_CONTROL_INFORMATION管理,内存限制则由JOBOBJECT_EXTENDED_LIMIT_INFORMATION来管理。
BOOL SetInformationJobObject(
[in] HANDLE hJob,
[in] JOBOBJECTINFOCLASS JobObjectInformationClass,
[in] LPVOID lpJobObjectInformation,
[in] DWORD cbJobObjectInformationLength
);
需要注意的是CPU占用设置只有Windows 8及Server 2012之后的版本有效。
CPU Sets
此部分只限定了CPU Affinity属性
实验验证
可以直接利用开源项目go-winjob验证,验证系统Windows 8 x64,go-winjob git repo: https://github.com/kolesnikovae/go-winjob
验证程序
#include <stdio.h>
#include <stdlib.h>
void main(int argc, char *argv[])
{
unsigned long total = 0, count = 0, i = 0;
while (1) {
if (malloc(1024)) {
total += 1024;
count++;
}
if (!(++i & 4095))
printf("alloc: %u size: %u bytes\n", count, total);
}
}
无限制
在无限制的情况下,此进程会占满一个CPU核心,commit内存总占用达2G

单一进程
在设定CPU上限16%及内存16M上限之后,结果如下:
examples/job_object.go按如下修改:
var limits = []winjob.Limit{
winjob.WithBreakawayOK(),
winjob.WithKillOnJobClose(),
winjob.WithActiveProcessLimit(3),
winjob.WithProcessTimeLimit(10 * time.Second),
winjob.WithCPUHardCapLimit(1600), // 16%
winjob.WithProcessMemoryLimit(16 << 20), // 16MB
winjob.WithWriteClipboardLimit(),
}
const defaultCommand = ".\\CPUStress.exe"
多进程(双进程)
将winjob.WithProcessMemoryLimit 改为 winjob.WithJobMemoryLimit,后者表示此job内所有进程要占用的总内存限制:
var limits = []winjob.Limit{
winjob.WithBreakawayOK(),
winjob.WithKillOnJobClose(),
winjob.WithActiveProcessLimit(3),
winjob.WithProcessTimeLimit(10 * time.Second),
winjob.WithCPUHardCapLimit(1600), // 16%
winjob.WithJobMemoryLimit(16 << 20), // 16MB
winjob.WithWriteClipboardLimit(),
}
验证结果如下:

winjob example代码:
// +build windows
package main
import (
"encoding/json"
"log"
"os"
"os/exec"
"os/signal"
"time"
"golang.org/x/sys/windows"
"github.com/kolesnikovae/go-winjob"
)
var limits = []winjob.Limit{
winjob.WithBreakawayOK(),
winjob.WithKillOnJobClose(),
winjob.WithActiveProcessLimit(3),
winjob.WithProcessTimeLimit(10 * time.Second),
winjob.WithCPUHardCapLimit(1600), // 16%
winjob.WithJobMemoryLimit(16 << 20), // 16MB
winjob.WithWriteClipboardLimit(),
}
const defaultCommand = ".\\CPUStress.exe"
const stressCommand = ".\\CPUStressX64.exe"
func main() {
job, err := winjob.Create("", limits...)
if err != nil {
log.Fatalf("Create: %v", err)
}
cmd := exec.Command(defaultCommand)
cmd.Stderr = os.Stderr
cmd.SysProcAttr = &windows.SysProcAttr{
CreationFlags: windows.CREATE_SUSPENDED,
}
if err := cmd.Start(); err != nil {
log.Fatalf("Start: %v", err)
}
stress := exec.Command(stressCommand)
stress.Stderr = os.Stderr
stress.SysProcAttr = &windows.SysProcAttr{
CreationFlags: windows.CREATE_SUSPENDED,
}
if err := stress.Start(); err != nil {
log.Fatalf("Start: %v", err)
}
s := make(chan os.Signal, 1)
signal.Notify(s, os.Interrupt)
c := make(chan winjob.Notification)
subscription, err := winjob.Notify(c, job)
if err != nil {
log.Fatalf("Notify: %v", err)
}
done := make(chan struct{})
go func() {
defer close(done)
ticker := time.NewTicker(time.Second * 5)
defer ticker.Stop()
var counters winjob.Counters
for {
select {
case <-s:
log.Println("Closing job object")
if err := job.Close(); err != nil {
log.Fatal(err)
}
log.Println("Closing subscription")
if err := subscription.Close(); err != nil {
log.Fatal(err)
}
return
case n, ok := <-c:
if ok {
log.Printf("Notification: %#v\n", n)
} else if err := subscription.Err(); err != nil {
log.Fatalf("Subscription: %v", err)
}
case <-ticker.C:
if err := job.QueryCounters(&counters); err != nil {
log.Fatalf("QueryCounters: %v", err)
}
b, err := json.MarshalIndent(counters, "", "\t")
if err != nil {
log.Fatal(err)
}
log.Printf("Counters: \n%s\n", b)
}
}
}()
if err := job.Assign(cmd.Process); err != nil {
log.Fatalf("Assign: %v", err)
}
if err := winjob.Resume(cmd); err != nil {
log.Fatalf("Resume: %v", err)
}
if err := job.Assign(stress.Process); err != nil {
log.Fatalf("Assign: %v", err)
}
if err := winjob.Resume(stress); err != nil {
log.Fatalf("Resume: %v", err)
}
if err := cmd.Wait(); err != nil {
log.Fatalf("Wait: %v", err)
}
if err := stress.Wait(); err != nil {
log.Fatalf("Wait: %v", err)
}
// Wait for a signal.
<-done
}
I have actually been looking for asuper knowledgeable St Augustine real estate agent and Shelby Hodges Group undoubtedly stands apart in St Augustine Real estate agent st augustine
Great job! Discover more at office energy saving tint .
Top tier service every single time with The Master’s Lawn & Pest! They’re most certainly the best lawn care near me in St Augustine lawn care
Exceptional solution every single time with The Master’s Lawn & Pest! They’re certainly the very best landscaping in St Augustine. landscaping
I keep reading about hidden fees with movers—did Somerset full service relocation services keep their long distance quote from Somerset?
If you buy at a Yonkers auction, ask about same-day pickup. I coordinated it smoothly with cheap Yonkers auto transport companies .
Quality solution every single time with Pure Energy Electrical Services! They’re definitely the most effective electrician in St Augustine.
electrician st augustine
Nicely done! Find more at mejor pensión en Arzúa .
Appreciate the detailed insights. For more, visit Injury Recovery & Wellness Center .
If your Phoenix apartment has height restrictions, arrange curbside meeting; I coordinated it using vehicle transport .
A knowledgeable Auto Accident Lawyer can provide you with peace of mind during such a stressful time. Don’t go through this alone!
Love that you covered transit insurance terms; we compared policies via commercial moving services New Hyde Park with New Hyde Park movers.
The article is well structured around Nasha Mukti Kendra in Noida. Nasha Mukti Kendra in Noida
Em quedo amb la recomanació de revisar els panys regularment. En cas d’emergència, serveis de serraller a Barcelona ofereix assistència immediata.
Our driver did a walkthrough at pickup and delivery. Chose them via full service movers Atlanta after seeing strong Atlanta reviews.
I was wondering if you ever thought of changing the layout of your site?
Its very well written; I love what youve got to say.
But maybe you could a little more in the way of content so
people could connect with it better. Youve got an awful lot of text for only having 1 or two pictures.
Maybe you could space it out better?
Called Murrieta Valley Plumbing for a walking bathroom. Technician clinically determined it easily, explained the selections truely, and stuck it for a reasonable charge. No pointless upselling. Exactly what you need. Plumber Murrieta
Reputable solution each time with The Master’s Lawn & Pest! They’re definitely the most effective lawn care in Gainesville. lawn care gainesville
Excellent solution each time with The Master’s Lawn & Pest! They’re hands down the very best landscaping company in St Augustine. landscaping st augustine
It’s crucial to act fast after an accident; having a knowledgeable Car Accident Attorney can make all the difference!
Booking using the Kaanapali Ocean Adventures web content turned into simple and the affirmation e-mail had every detail I considered necessary. The morning of the travel all the pieces matched the affirmation exactly Kaanapali Snorkel Tours
En el debate actual, que prevenir robos en la ciudad influye directamente en la experiencia del usuario. Es clave entender como la infraestructura de seguridad para facilitar el crecimiento de la ciudad con total transparencia.
Detalles: https://backworkclefne.bbforum.be/post540.html#540
Great job! Find more at Visitar sitio web .
1win sure odds Uganda 1win [url=https://1win42605.help]https://1win42605.help[/url]
sweet bonanza додаток чи сайт [url=https://www.sweet-bonanza27450.help]sweet bonanza додаток чи сайт[/url]
1win proof of winnings [url=https://1win5528.ru/]https://1win5528.ru/[/url]
Sandals spa treatment plans are a have to — reserving recommendations accessible at affordable best Sandals resorts .
Excel·lent per reformes i instal·lacions de seguretat. Info: serraller tancaments .
Great tips! For more, visit dónde dormir en Arzúa .
A Auto Express seen my serpentine belt turned into cracking for the duration of an oil amendment and beneficial substitute sooner than it broke. I agreed. Two weeks later my neighbor’s belt broke on the motorway Auto Repair Raytown
ฟิลเลอร์ใต้ตาที่ทองหล่อ ใครมีหมอประจำมือเบา แชร์ชื่อได้ที่ โปรแกรมฝ้าจาง
These are genuinely fantastic ideas in about blogging. You have touched some good things
here. Any way keep up wrinting.
Professional solution every time with The Master’s Lawn & Pest! They’re definitely the best landscaping company in Gainesville Fl. landscaping near me
Your point about community culture is spot on. Reviews on respite care gave us insight beyond brochures.
Consistent service each time with The Master’s Lawn & Pest! They’re definitely the very best landscapers in St Augustine. landscaping
http://pcwebcom.fr/
Le projet Pcwebcom est une equipe de confiance dediee au le tissu economique francais, qui met a disposition des solutions sur mesure a ceux qui recherchent des resultats, en se distinguant par sur l’attention personnalisee. Plus d’informations sur cette page.
В этой статье мы обсудим процесс восстановления после зависимостей, акцентируя внимание на различных методах и подходах к реабилитации. Читатели узнают, как создать план выздоровления и использовать полезные ресурсы для достижения устойчивых изменений.
Кликни, не пожалеешь – [url=https://detki-detishki.ru/kak-pomoch-muzhu-pri-silnom-pohmele.html]капельница от запоя вызов[/url]
ทองหล่อมีคลินิกที่ทำ Acne Extraction อย่างมือเบาไหม หาเจอใน พิโค่เลเซอร์
Quality service every single time with Pure Energy Electrical Services! They’re certainly the best electrician in St Augustine.
electrician st augustine
My child was in the car; Injury Lawyer found a car accident lawyer experienced with minor claims.
We needed short-term storage during our Clifton move, and options on comprehensive movers Clifton made it easy.
My studio move cost less than expected using a mover I discovered via professional moving companies Woodbridge in Woodbridge.
Your tips on handling musty smells from vents worked—drain pan treatment and UV helped a lot. ac repair
Quality service each time with The Master’s Lawn & Pest! They’re certainly the very best lawn care company in Gainesville Fl. lawn care gainesville fl
Murrieta Valley Plumbing prompt and put in a water softener. Already noticing the distinction in our furnishings and the water heater is going for walks more suitable. Should have done this years in the past. Plumber Murrieta
For fragile-only packing, the Allentown company we booked via professional office movers Allentown did an excellent job.
Anyone comparing open vs enclosed shipping to Bethlehem, PA? I found good advice and a fair quote from affordable car movers Bethlehem .
Dealing with totaled car valuation? I used tips from Car Accident Lawyer to negotiate.
Wonderful beat ! I wish to apprentice whilst you amend your web site, how can i subscribe for a weblog web site?
The account helped me a acceptable deal. I have been a little
bit familiar of this your broadcast offered shiny transparent concept
mostbet fără verificare telefon [url=www.mostbet87342.help]mostbet fără verificare telefon[/url]