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
}
Photos, medical records, and expert reports were essential— Car Accident Lawyer showed me how lawyers build that evidence.
คุณคิดว่าราคาเป็นปัจจัยหลักในการตัดสินใจซื้อหรือไม่? ### ร้าน ไฟหน้ารถยนต์ ใกล้ ฉัน
My vehicle-fill became inflicting stealth overflows; leading pool service company adjusted it and stored water.
Pretty section of content. I just stumbled upon your blog and in accession capital to claim that I get in fact loved account your weblog posts. Any way I’ll be subscribing to your augment and even I fulfillment you access persistently rapidly.
https://teletype.in/@avtobloggerua/09zDUARfxD-
мелбет кз вход по email [url=https://www.melbet15709.help]мелбет кз вход по email[/url]
First-rate solution each time with The Master’s Lawn & Pest! They’re most certainly the most effective lawn care near me in Gainesville. lawn care gainesville
цветы в москве с доставкой недорого на дом онлайн заявка [url=http://dostavka-cvetov777.ru]цветы в москве с доставкой недорого на дом онлайн заявка[/url] .
мелбет кз вход с компьютера [url=www.melbet15709.help]www.melbet15709.help[/url]
I recently moved to Puyallup, and I was shocked by how many pests I encountered in my new home! After doing some research on pest control options, I found that local services are crucial for effective solutions licensed exterminator near me
The impact of weather on roofs cannot be understated; great insights shared here! Check out reliable services at Roofing contractor Exquisite Roofing and Exteriors !
For motorcycle crashes, lane visibility and headlight usage often factor into fault. Evidence list: Car Accident .
Anyone in Glastonbury CT seeking a licensed roofing contractor should look at roofing contractor .
Wow, the sale on flags at USA flag website help became too precise to skip up – made a few widespread purchases!
melbet Казахстан скачать [url=http://melbet15709.help/]melbet Казахстан скачать[/url]
I honestly prefer playing on my phone these days. It is so much faster to log in with Face ID instead of typing out a long password on my laptop. Plus, the portrait mode layouts are way more intuitive when I am just killing time casino app vs mobile site
Post-op implant care instructions from Boulder clinicians were helpful on local dentist boulder .
Nothing beats the feeling of receiving new flags within the mail from your favorite retailer like peace flags for home decor !
Great advice here! Knowing about your legal options via Auto Accident can lead to better outcomes after an accident.
After a car accident, trust Wall Family Chiropractic Center to provide expert evaluations and treatments for a full recovery. Parkland chiropractic office
It makes sense that mobile play is taking over. I personally love how the HTML5 instant play tech lets me jump straight into a game without waiting for downloads https://sticky-wiki.win/index.php/Why_Live_Casino_is_the_Undisputed_King_of_the_Mobile_Shift
Clear overview of NEC updates; I checked local amendments through residential lighting Baton Rouge .
Additionally, their pricing was very reasonable for the high-quality service provided. I felt that I received great value for the investment and would highly recommend them to anyone looking for pressure washing services. Christmas Light Installation Tampa Bay Pressure Washing
Excellent troubleshooting flow for tripping breakers. I cross-checked with notes on Irving certified electrician .
Always keep in mind that insurance companies are not on your side; having an aggressive ### anyKeyword### ensures they respect your claim. Truck Accident Attorney
This article makes planning my next event so much easier with this great tent selection! Bounce Genie Land O Lakes
For cedar shake to asphalt conversions in Glastonbury, Connecticut, Exteriors of CT roofing contractor did excellent work.
I definitely prefer mobile play these days, mainly because using Face ID to log in is so much faster than typing out my password every time I open the desktop site. It’s been a game changer for quick sessions while I’m on the move https://beckettsbestword.trexgame.net/is-begambleaware-legit-a-practical-guide-to-gambling-support-in-the-uk
melbet slots играть [url=http://melbet15709.help/]melbet slots играть[/url]
mostbet cashout qanday [url=http://mostbet47183.help/]http://mostbet47183.help/[/url]
I’m flying my flag to honor mentors and heroes. Read: 2a flag indoor wall decor for home or office
I definitely agree that mobile is taking over, though it is a double-edged sword. Being able to play in portrait mode is a game changer for quick sessions on the bus, but I’ve noticed that live roulette really drains my battery way faster than other games Go to the website
Great job! Discover more at cocinas con isla Granada .
มื้อเช้าก็ดี มื้อดึกก็รอด ผู้กำกับสับไก่ข้าวมันไก่ธนาพล เวลาเปิดปิดที่ ข้าวมันไก่
1win bono de bienvenida [url=1win05634.help]1win bono de bienvenida[/url]
Здравствуйте!
Проблемы с техникой? Мы знаем, как сделать её лучше!
Каждая деталь важна, когда речь идет о вашем бизнесе. Мы предлагаем вам не просто устранение неисправностей, а полноценную модернизацию вашего оборудования, что позволит повысить его эффективность и надежность. Наши специалисты настроят каждую деталь на максимальную отдачу, обеспечивая бесперебойную работу и долгосрочную эксплуатацию.
Полная информация по ссылке – https://dag-techservice.ru/sitemap.xml
сервисное обслуживание оборудования челябинск, ремонт насосного оборудования, сервисное обслуживание оборудования лабораторного
сборка и наладка шкафа управления, [url=https://dag-techservice.ru/cases/]Кейсы — DAG TechService[/url], процесс сервисное обслуживание оборудования
Удачи и комфорта в жизни!
[url=https://futuros-talentos.com/tutorial-diseno-grafico-colegios-y-ampas/#comment-56678]Модернизация с минимальными затратами, максимальными результатами[/url] a72f07_
Hello, of course this paragraph is in fact pleasant and I
have learned lot of things from it on the topic of blogging.
thanks.
A skilled attorney will fight for your rights and ensure fair treatment throughout the claims process—connect with one via Truck Accident Lawyer !
Sharing my story while flying my flag with pride. Visit: visit website
Had a good timeline sooner than striking my space available to buy. roofer near me obtained the restoration accomplished briskly with first rate scale back appeal.
ใครมีคำแนะนำเกี่ยวกับการเลือกซื้อและติดตั้งไหม?? ร้านเปลี่ยนหลอดไฟรถยนต์ ใกล้ฉัน
мелбет кз android app [url=http://melbet15709.help/]мелбет кз android app[/url]
Thanks for the practical tips. More at Injury Lawyer .
Before calling a plumber for a going for walks toilet, I checked the flapper, fill valve, and chain duration. Simple fixes kept me a carrier name—there’s a quickly diagnostic flowchart on plumber .
If you’re ever locked out in Orlando, make sure to call a risk-free locksmith. I had a major trip with one not too long ago! locksmith
1win registro con DNI [url=http://1win05634.help/]http://1win05634.help/[/url]
мелбет кз скачать на планшет [url=http://melbet15709.help]мелбет кз скачать на планшет[/url]
A trusted Injury Lawyer will ensure that you’re not taken advantage of by insurance companies.
Just booked a cleaning in Boulder; price transparency and online scheduling at dentistry boulder made it easy.
mostbet mobil tolov [url=www.mostbet47183.help]www.mostbet47183.help[/url]
The right walker can transform leash manners; mine is from weekend dog walkers Chandler .