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=www.melbet95634.help]www.melbet95634.help[/url]
New to the gym in Melbourne? Start safely with a personal trainer from personal trainer melbourne .
I appreciated the budget-friendly hardscape ideas. I saved a few DIY projects from landscaping companies mississauga to try this weekend.
From my Ontario home yard drainage, I realized to plan ahead. I’m in Toronto and that read helps; hardscaping near me is useful.
Your health should be your priority post-accident; let a skilled Truck Accident Attorney handle the legal matters for you!
I appreciate this reminder about road safety—let’s all do our part to prevent accidents! Car Accident Lawyer
Clear, practical post. If readers want example timelines and cost estimates for Toronto additions, check house additions gta for more details.
Сериал «Твин Пикс» 2017 года — не просто продолжение культовой истории, а прыжок в пропасть, где время гниёт, а реальность разваливается. Агент Купер в исполнении Линча — уже не тот непоколебимый детектив, а фигура, разбитая на осколки и рассеянная по разным измерениям. Маленький городок в туманах северо-запада снова хранит тайны — только теперь мрак в нём гуще, а иные измерения не проглядывают сквозь повседневность, а буквально разрывают её. Ищете твин пикс смотреть онлайн? Смотреть все 18 серий с озвучкой LostFilm и Amedia можно на tvin-piks-kinogo.cc без регистрации в любое время. Режиссёр не греется в лучах прошлого — он вскрывает ностальгию как хирург: затяжные тишины, внезапное насилие и режущая слух музыка. В каждом эпизоде ощущается главное: привычный мир — лишь тонкая плёнка над тёмной бездной бессознательного.
This was quite helpful. For more, visit assisted living .
1win cómo depositar con Plin [url=https://www.1win05634.help]https://www.1win05634.help[/url]
Thanks for the great explanation. Find more at pressure washing Melville .
Appreciate the DIY hacks. When it’s time for an expert surface, attempt recurring house cleaning Calgary .
Are there any Alzheimer’s support groups connected to local assisted living? Saw links on senior care .
Appreciate the insightful article. Find more at senior care .
Touring multiple communities made a big difference for us. elderly care helped create a thorough tour checklist.
I recently had a pest problem in my home, and I was amazed by the effective solutions offered by local services. It’s crucial to choose a knowledgeable pest control provider in Puyallup to ensure a pest-free environment exterminator in my area
pin-up aviator yüklə [url=pinup48127.help]pinup48127.help[/url]
ХолдСервис — специализированная компания по ремонту и монтажу холодильного и теплового оборудования в Восточном административном округе Москвы. Свыше 15 лет специалисты компании проводят диагностику и ремонт промышленных холодильников, чиллеров, низкотемпературных камер, ледогенераторов, фризеров и скороморозильных агрегатов. Выезд мастера осуществляется бесплатно на объект заказчика. Все подробности об услугах и условиях сотрудничества — на сайте https://holdservis.ru/ оставьте заявку и мастер приедет в удобное время. Отсутствие посредников в цепочке услуг позволяет компании предлагать конкурентные цены и неизменно качественный результат.
This was highly helpful. For more, visit assisted living .
Anxiety often needs both cognitive and somatic tools; IFS therapy offers integrated intensive options.
Vocational losses can be claimed too. I learned here and at Car Accident Attorney .
สนใจทรีตเมนต์หน้าใสก่อนถ่ายรูป แถวทองหล่อมีแบบด่วนๆ ไหมคะ ดูตัวเลือกใน โปรแกรมฝ้าจาง
The baking soda and vinegar trick works wonders for minor clogs! For anything stubborn, I usually consult Tennessee Standard Plumbing and Drain or check plumber Maryville for professional solutions.
La rapidez y eficiencia del equipo de cerrajero barcelona me sorprendió gratamente.
This is a must-read for new drivers. I tell my friends to save battery jump start .
Glad I stumbled upon this article; it’s full of actionable insights that can save homeowners money and time in the long run!! roofing services
mostbet si krok za krokem vyvinul jedním mezi nejznámějších brandů v
sféry digitálního házecích her plus herních platform když její aktivita se neomezuje limitováno pouze na určité území,
jelikož, služby mostbet cz
umožňují širokou paletu variant sázkařům
napříč celé kontinentu. Založení Mostbet bylo charakterizuje snahou kombinovat klasické hodnoty hazardu za pomoci novými softwary, a tím přineslo aplikaci okamžitě dosáhnout uznání mezi ostřílenými sázkaři také nové uživatele.
Mostbet casino umožňuje kromě atletické sázkové možnosti, rovněž také tradiční casino tituly, což láka rozsáhlou veřejnost.
Díky své tradici plus pevnějšímu chodu se Most Bet navázal důvěru důvěryhodného poskytovatele
v oblasti internetového sázení. Společnost by se orientuje na otevřenost, stabilitu i férové podmínky,
a tím znamená nezbytné k posílení stálé loajality sázkařů.
Jelikož, že Most Bet app umožňuje okamžitý přístup k sázení i hře přímo
z mobilního zařízení, sázkaři jsou schopni používat možnosti neustále i
kdekoli, aniž to byli závislí PC. Možnost instalace app přes
Most Bet download zajišťuje, aby každá funkce jsou optimalizované za
účelem efektivní i snadný herní zkušenost. Dalším faktorem, který přispívá k pověsti
Mostbet, znamená široká volba bonusů, jež motivují nové i
stálé sázkaře, ať už to jedná o startovní Most
Bet bonus nebo pravidelné nabídky na kasino prostředí.
Dějiny Mostbet prokazuje, že platforma stránka byla schopna rychle adaptovat se
k žádosti trhu, adaptovat nabídku i inovovat, a tím zajišťuje jeho pevnou polohu v rámci soutěži.
Obecně můžeme prohlásit, že silné základy, sloučení tradičního i nového postupu a intenzivní orientace ohledně sázkařský zážitek představuje páteř
úspěšnosti Most Bet a své možností třeba Mostbet CZ či Most Bet Casino, což z
něj vyhledávanou možnost ohledně velkou skupinu sázkařů.
If you had a pre-accident job offer, a car accident lawyer at car accident lawyer documented lost opportunity.
Are there fall risk screenings during admission? I’m reviewing clinical policies on elderly care .
pin-up bepul tikish 2026 [url=http://pinup08694.help/]http://pinup08694.help/[/url]
Valuable information! Find more at residential assisted living cathedral city .
Terrific insights on senior care options! For those exploring customized assistance, have a look at senior care for caring assisted living resources.
I appreciated the budget-friendly hardscape ideas. I saved a few DIY projects from landscaping mississauga to try this weekend.
As a GTA resident, I prefer clear maintenance checklists. This article fits, and I regularly use landscaping companies toronto .
aviator game 1win [url=http://1win5529.ru]http://1win5529.ru[/url]
Solid overview of timelines and common delays. For contractor checklists and permit pointers in Toronto, modern addition to old house toronto was a useful reference for us.
This breakdown hits on the exact frustrations I’ve had with agencies recently. I keep a personal checklist of “what they won’t tell you on the sales call” because the gap between the pitch and the actual execution is massive https://wiki-room.win/index.php/Top_15_Best_European_SEO_Agencies_-_In-Depth_Market_Analysis_(2026)
Memory treatment transitions can be challenging. We situated a community with a smooth assisted living to memory care pathway via memory care .
I mark the exact location on my phone map and save it—tip via Auto Accident .
Photos of the scene helped my claim. Car Accident Attorney has a checklist and a lawyer can ensure you capture what matters.
Drug administration can be overwhelming. We located trusted assistance and oversight by means of respite care in an assisted living community.
actualizar pin-up app [url=http://pinup62718.help/]http://pinup62718.help/[/url]
1win decimal odds [url=http://1win5529.ru/]http://1win5529.ru/[/url]
Wrongful death after a collision requires compassionate legal guidance. Learn more at Motorcycle Accident Lawyer .
mostbet aviator стратегия [url=https://www.mostbet80295.help]https://www.mostbet80295.help[/url]
pin-up hesab balansı [url=https://pinup48127.help]https://pinup48127.help[/url]
мелбет ставки на спорт [url=melbet95634.help]melbet95634.help[/url]
Thanks for the detailed post. Find more at memory care .
Great job! Discover more at Kerner Law Group PLLC .
We value how BBQ restaurant capital region labels sauces by warmth degree– clever for large teams.