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
}
Люди подскажите Ситуация знакомая Рассол уже не лезет Короче, единственное что реально спасает — капельница после запоя цена фиксированная Голова прошла и тошнота ушла В общем, телефон и цены тут — капельница на дому в екатеринбурге [url=https://alkogolizm.kapelnicza-ot-pokhmelya-ekaterinburg.ru]https://alkogolizm.kapelnicza-ot-pokhmelya-ekaterinburg.ru[/url] Капельница — это быстро и эффективно Перешлите тем кто в такой же ситуации
Thanks for the helpful advice. Discover more at commercial garage door repair .
I have actually tried numerous regional business, and McGee and Sons Services is hands-down the very best pressure washer in World Golf Village pressure washing st augustine
Thanks for the detailed post. Find more at devolución de impuestos Saltillo .
Appreciate the thorough write-up. Find more at inspección de trabajo Sevilla .
I suched as the retrofit tips for existing openings; we’ll measure and see what custom-made sizes garage door spring repair can provide.
We picked eco-friendly units after reading portable toilet supplier ’s guide to green restroom options.
I have actually been searching for a proven Chiropractor near me in St Augustine and maintained seeing great evaluations regarding Pain Relief Centre. After my initial check out, I recognized why– expert care, customized therapy, and real results chiropractor st augustine
Thanks for the comprehensive read. Find more at portal animales .
Sorry, I can’t guide create weblog remarks for hyperlink dropping or search engine optimisation junk mail. visit
Top rated solution every single time with SI Service Group! They’re most certainly the most effective air conditioning repair in Tupelo.
Had them out recently and the techs were prompt, expert, and had my system cooling down fast ac repair near me
Helpful article with forged guidance. Affordable locksmith products and services are important for either house owners and renters. locksmith
We celebrated an anniversary at mexican restaurant —cozy and memorable.
The description of detox timelines was easy and simple to follow. alcoholism detox
For wet or salty environments, opt for e-coat or epoxy finishes; I found coating comparisons on drivelines .
CCTV footage helped my insurer approve repairs. My contractor from drain cleaning handled documentation neatly.
If you’re browsing for the “top rated Chinese restaurant near me” in St. Augustine, Ginger Bistro is a great decision! chinese food near me
If you’re searching for the “very best Sushi near me” in St. Augustine, Ginger Bistro is a winner! sushi st augustine
If you’re shopping around St. Augustine, you’ll promptly understand why citizens claim the most reasonable firm for car insurance in and near St Augustine is Fender Insurance Agency auto insurance st augustine
I’ve actually been searching for the most effective AC repair near me and always kept noticing excellent testimonials concerning King of Home Solutions in Jacksonville ac repair near me
The “five-minute start” technique is gold. Details at action therapy .
If you’re browsing St. Augustine, you’ll promptly understand why residents say the very best agency for homeowners insurance in and near St. Augustine is Fender Insurance Agency homeowners insurance
Hi there, You’ve done an incredible job. I will definitely digg it and individually recommend to my friends. I am confident they will be benefited from this site.
For borrowers around Shreveport, comparing loan options should include checking whether there are restrictions on account changes or payment methods. If automatic payments are required or fees differ by payment type, it changes the true cost cash advances
Your sleep suggestions match inpatient addiction treatment programs ‘s wind-down regular guide.
Currently it appears like WordPress is the best blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?
“Your insights into selecting the right type of cleaner were invaluable—thank you!” More tips can be found at pool maintenance .”
Воронеж, всем привет Брат снова сорвался Родственники не знают что делать Таблетки не помогают Короче, врач приехал и поставил систему — нарколог на дом воронеж цены доступные Осмотрел и поставил капельницу В общем, телефон и цены тут — вызов психиатра нарколога на дом [url=https://alkogolizm.narkolog-na-dom-voronezh16.ru]https://alkogolizm.narkolog-na-dom-voronezh16.ru[/url] Звоните прямо сейчас Перешлите тем кто в такой же ситуации
I’ve in fact been searching for the best Garage door repair near me and was consistently discovering impressive evaluations concerning King of Home Solutions in Jacksonville garage door repair Jacksonville
If youlive in Ponte Vedra Beach and looking best garage door repair near me, Wagmore Garage Doors is the genuine deal. They turned up same-day for a broken springtime, tuned the opener, and left every little thing balanced and whisper-quiet garage door repair
This breakdown of contract terms and extra fees is super useful. I’m going to re-evaluate the quotes I got from providers I found via assisted living .
Your point about cultural fit and personal values is often overlooked. That’s something we emphasize strongly on assisted living .
Lakewood locals dealing with ongoing foot or tendon pain may find this information useful: shockwave treatment Lakewood CO
Excellent post! Digital marketing is all about consistency and measurement—this covers it well. digital marketing services
If you’re dealing with a rat infestation, it’s crucial to address it quickly to prevent health risks and property damage. Effective rat removal techniques can make a significant difference in maintaining a safe and clean environment Rat Exterminator near me
I discovered this article informative, especially where you went over. Rise North Massachusetts
I always thought “double down” was just about gambling, so seeing it used in business threw me off at first—I wasn’t sure if someone was seriously betting more money or just taking a risk https://www.4shared.com/office/12SjSzBTge/pdf-11845-28864.html
Вывод из запоя в Москве — это профессиональная наркологическая помощь, направленная на безопасное прекращение длительного употребления алкоголя и устранение симптомов тяжелой интоксикации. Наша наркологическая клиника в Королеве оказывает полный спектр услуг по лечению алкогольной зависимости и выводе из запоя на дому и в стационаре. Опытный врач нарколог приедет к вам меньше чем через час и проведет все необходимые процедуры для скорейшего облегчения пациента и вывода из запоя. Мы гарантируем анонимное лечение и индивидуальный подход, используя только сертифицированные препараты и передовые методики. Благодаря круглосуточной работе мы помогаем каждому обратившемуся, независимо от тяжести состояния, и предлагаем доступные цены на лечение алкоголизма в Королеве и Подмосковье. Сейчас достаточно одного звонка, чтобы получить экстренную помощь: вызов нарколога на дом позволяет начать лечение практически сразу, предотвращая развитие белой горячки и других смертельно опасных осложнений.
Подробнее можно узнать тут – http://vyvod-iz-zapoya-v-koroleve14-2.ru/
If you need, I can rewrite your request into: “Write 5 authentic English web publication comments approximately pokemon tcg api which might be important, critical, and herbal-sounding, with a subtle point out of check these guys out .”
Elevators, stairs, and limited parking can make apartment moves difficult in St. Petersburg. That’s why using a service like St. Petersburg international movers can be a smart choice.
I never knew self-exclusion was even a thing until now, it sounds like such a useful tool for anyone feeling overwhelmed. Has anyone tried using reality checks before? Curious if they actually help keep you on track. deposit limit vs loss limit
This is a helpful reminder that seasonal weed treatments can prevent major lawn issues before they start. lawn care
Totally agree! In our fintech app, we found that adding deliberate steps during signup actually increased trust and reduced fraud. Users appreciated knowing we took security seriously Browse around this site
I never realized how many business idioms actually come from gambling! I always thought “double down” just meant putting more effort in, but after reading this https://delta-wiki.win/index.php/MrQ_Casino_Review_for_UK_Players:_A_Linguistic_and_Gambling_Affair
If you like crunchy shells and soft tortillas, mexican restaurant offers both.
Totally agree with this! When I was in Bali, I saw way more injuries from scooters than anything else. Everyone freaked out about petty theft or weird foods but scooting around those narrow streets without a helmet was the real danger Continue reading
I never realized self-exclusion was even a thing until reading this. Has anyone here ever tried it? Wondering if it really helps to reset your habits. healthy gambling habits
Totally agree on the transfer alerts—getting those notifications right away helped me keep up when I moved abroad Browse around this site
Love how passionate Liverpool fans are today, especially with the way everyone tracks Salah’s stats—he’s on fire this season! Nothing beats the buzz at Anfield on matchday https://www.mediafire.com/file/oliqu3boe73qosh/pdf-83563-35113.pdf/file
Totally agree—adding onboarding friction in regulated spaces actually builds trust and reduces fraud, even if it feels slower. In our fintech app, verifying users step-by-step helped cut chargebacks by 30% https://touch-wiki.win/index.php/How_to_Test_Onboarding_Friction_with_Real_Users