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
}
Hey are using WordPress for your site platform? I’m new to the blog world but I’m trying to get started and create my own. Do you require any html coding knowledge to make your own blog? Any help would be really appreciated!
https://salonsharm.com.ua/perekhidnyky-dlya-obmanok-h7-yak-obiity.html
If your Houston office needs master key systems, the team at locksmith company Houston can guide you.
Thanks for the helpful information. Anyone seeking an assisted living home can start their search with assisted living for curated options.
Howdy! This post couldn’t be written any better! Reading this post reminds me of my previous room mate! He always kept talking about this. I will forward this page to him. Pretty sure he will have a good read. Thanks for sharing!
https://olivetc.com.ua/tesla-model-s-plaid-retrofit-far-dlya-tykh-khto-ts.html
Hello, for all time i used to check blog posts here early in the dawn, as i like to learn more and more.
https://tayger.com.ua/mitsubishi-lancer-x-retrofit-far-bi-led.html
Great tips! For more, visit assisted living .
Nicely done! Find more at assisted living .
В этой публикации мы обсуждаем современные методы лечения различных заболеваний. Читатели узнают о новых медикаментах, терапиях и исследованиях, которые активно применяются для лечения. Мы нацелены на то, чтобы предоставить практические знания, которые могут помочь в борьбе с недугами.
Хочешь знать всё? – [url=https://mchs-orel.ru/psixologicheskie-osnovy-reabilitacii-narkozavisimyx/]Похмельная служба в Москве[/url]
The article’s reminder to involve seniors in decisions is key. assisted living has conversation guides for families.
Aposta pequena. Fica mais tempo.
вызвать нарколога на дом воронеж [url=https://narkolog-na-dom-voronezh-13.ru]вызвать нарколога на дом воронеж[/url]
For most up-to-date information you have to pay a visit world wide web and on internet I found this website as a best website for hottest updates.
https://imperialgroup.com.ua/sylikonovyi-hermetyk-dlya-far-koly-ioho-vykorystov.html
Thanks for raising awareness about electrical hazards. I learned a lot from my report via home inspection .
Attractive component to content. I just stumbled upon your site and in accession capital to claim that I acquire actually enjoyed account your weblog posts. Anyway I will be subscribing for your feeds or even I success you get entry to consistently quickly.
https://compromat.in.ua/shcho-kazhut-na-sto-chomu-maistry-ne.html
Обзор посвящён процессу восстановления после зависимостей. Мы расскажем о различных этапах реабилитации, поддерживающих ресурсах и важности мотивации в достижении устойчивого выздоровления.
А что дальше? – [url=https://www.pravda-tv.ru/2025/09/17/627533/chto-alkogol-razrushaet-7-organov-kotorye-stradayut-silnee-vsego]«Похмельная служба» в Люберцах[/url]
Hello mates, pleasant paragraph and fastidious urging commented at this place, I am actually enjoying by these.
https://vedanta.dp.ua/test-draiv-naboriv-dlya-khimichnoho-poliruvannya-f.html
Appreciating the time and energy you put into your website and in depth information you offer. It’s awesome to come across a blog every once in a while that isn’t the same unwanted rehashed material. Great read! I’ve bookmarked your site and I’m adding your RSS feeds to my Google account.
https://para-dise.com.ua/laifkhak-yak-zaminyty-korpus-fary-bez.html
In my experience, the best time for drywall repair is before any furniture is moved back in after renovations. I learned this from an article on drywall repair denver that talked about staging your painting project in logical steps.
We needed a fragrance-free option; Sarasota cleaning company accommodated easily.
Good tips on troubleshooting. When it got serious, I called https://www.google.com/maps/place/?q=place_id:ChIJEbVMGMIiVIgRKsK_8pgXjAI in Mint Hill.
Good info on hydro jetting vs. traditional snaking. I like the idea of a more thorough cleaning. I saw that Portable Toilet Rental offers hydro jetting for main lines and stubborn clogs.
Well explained. Discover more at memory care .
Незамедлительно после вызова нарколог приезжает на дом для детального осмотра. Врач измеряет жизненно важные показатели, такие как пульс, артериальное давление и температура, и собирает краткий анамнез, чтобы оценить степень алкогольной интоксикации. Эта диагностика является основой для разработки индивидуального плана терапии.
Получить дополнительную информацию – [url=https://kapelnica-ot-zapoya-lugansk-lnr0.ru/]вызвать капельницу от запоя луганск[/url]
Nicely detailed. Discover more at assisted living .
Great customer service and honest advice— septic tank pumping is my go-to for septic needs.
Buscas long-tail em Fortune Ox ficaram mais específicas em 2026. Galera pede variância, não vibes.
Clear communication with families was a must. We checked family portal features on memory care .
Break remains are an excellent trial run. We scheduled a short-term stay to check the fit through elderly care prior to choosing.
Eating and nourishment make a huge distinction. We located aided coping with diet professional support via memory care .
I enjoyed this read. For more, visit roofers company Jennings .
I’m tired of cold floors in winter. Heard that insulating the crawl space with spray foam from HVAC Service Conway SC can really help with that.
Nice job explaining noise sources. For Fayetteville AC Repair, reach out to central AC installation Fayetteville .
Builder punch lists benefit from independent eyes. Learn more at home inspector .
Your emphasis on protecting adjacent surfaces (cabinets, fixtures, etc.) is spot on. Our last contractor, found via residential painting denver , masked and taped everything with impressive precision.
Good advice — for rodent prevention for LA rentals, see mice control near me .
My kitchen and bathroom drains both show signs of partial blockage. I’ll be calling Septic Tank Cleaning for a full drain cleaning and system evaluation.
Sciatic pain was making my life miserable, but the team here knew exactly what to do. I’m finally comfortable again. Chiropractor near me
Very informative write-up. Garage Door Repair Tucson upgraded my springs to the right cycle rating. Tucson garage door opener service
Hi, i read your blog from time to time and i own a similar
one and i was just curious if you get a lot of spam comments?
If so how do you prevent it, any plugin or anything you can advise?
I get so much lately it’s driving me crazy so any support is very much appreciated.
Homeowners inside the Phoenix edge praise Phoenix Home Remodeling for skilled communication and responsive updates. Phoenix remodeling bathroom
Let’s keep striving towards greatness while uplifting spirits others surrounding us elevating st residential plumber in Sandpoint
В этом исследовании рассмотрены методы лечения зависимостей и их эффективность. Мы проанализируем различные подходы, используемые в реабилитационных центрах, и представим данные о результативности программ. Читатели получат надежные и научно обоснованные сведения о данной проблеме.
Проследить причинно-следственные связи – [url=https://www.smolmed.ru/narkolog-na-dom-komu-on-mozhet-pomoch/]стоп алко[/url]
http://botondellamada.es/
El proyecto Botondellamada se presenta como una estructura de confianza dedicada al tejido empresarial espanol, que pone a disposicion un enfoque integral a quienes buscan resultados, con foco en la confianza y la transparencia. Descubre todos los detalles en el sitio oficial.
Этот обзор содержит информацию о передовых достижениях в области медицины. Мы разберем инновационные технологии, которые меняют подход к лечению и диагностике, а также их влияние на эффективность оказания медицинской помощи.
Что ещё? Расскажи всё! – [url=https://www.serdechno.ru/enciklopediya/material/zapiski/12971.html]стоп алко новороссийск[/url]
The part on hydro-jetting frequency is spot on. We do semiannual jetting and quarterly pumping based on effluent TSS/FOG readings. Calculator at pipeline jetting services helped set intervals.
Appreciate this! Finding metal roofing near me with quick lead times was tough, so book early if you can. residential metal roofing Los Angeles
TripScan — это современный онлайн-сервис для создания уникальных и персонализированных туристических маршрутов. Забудьте о часах, потраченных на изучение форумов и путеводителей. С трипскан планирование путешествия превращается в увлекательный и простой процесс. Сервис помогает подобрать достопримечательности, отели, рестораны и развлечения, идеально подходящие именно вам.
[url=https://trip75c.co]trip scan [/url]
* Персонализация: Создавайте маршруты, основываясь на ваших интересах, бюджете и времени.
[url=https://trip75c.co]tripscan [/url]
* Экономия времени: Вся необходимая информация собрана в одном месте.
[url=https://trip75c.co]tripscan сайт [/url]
* Удобство: Планируйте поездки с любого устройства, где есть интернет.
[url=https://trip75c.co]tripscan сайт [/url]
* Вдохновение: Находите новые, неизведанные места и идеи для путешествий.
[url=https://trip75c.co]tripscan сайт [/url]
Чтобы воспользоваться всеми преимуществами платформы, необходимо выполнить простой трипскан вход в личный кабинет.
1. Перейдите на трипскан сайт через ваш браузер.
2. Нажмите кнопку «Войти» или «Регистрация».
3. Введите свои данные или используйте быструю авторизацию через социальные сети.
https://trip75c.co
tripscan РІС…РѕРґ
Aktualny Darmowy kod promocyjny Mostbet to idealna propozycja dla nowych uzytkownikow. Wpisujac QWERTY555, mozna otrzymac bonus bez dodatkowych oplat oraz darmowy zaklad. Kod promocyjny darmowy zaklad Mostbet dzisiaj pozwala przetestowac oferte bukmachera bez ryzyka. Bonus powitalny obejmuje rowniez procent od pierwszego depozytu. To jedna z najlepszych promocji dostepnych obecnie online.
Oficjalna strona bukmachera Mostbet https://elubin.pl/stats/articls/?kod_promocyjny_mostbet_polska_bonus_powitalny.html
Their collaboration with purchasers to tailor spaces is tremendous—Henson Architecture regularly nails the quick. Explore greater by way of henson architecture near me .
В данной статье мы поговорим о будущем медицины, акцентируя внимание на прорывных разработках и их потенциале. Читатель узнает о новых подходах к лечению, роли искусственного интеллекта и возможностях персонализированной медицины.
Уникальные данные только сегодня – [url=https://gipertoniya.net/forum/kapelnitsa-ot-zapoya-osobennosti-protseduryi-vyibor-medikamentov-i-polza-infuzionnoy-metodiki.html]Похмельная служба Москва[/url]