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
}
Thanks for the informative content. More at servicios para personas mayores .
This is precisely what I considered necessary. I put forward bulldog movers for any cross around Maryland.
Martial arts not only enhance physical conditioning yet also instill technique and focus in specialists. It’s interesting to see exactly how various designs, from karate to jiu-jitsu, offer distinct benefits Denver Taekwondo
Any recent price spikes due to fuel surcharges? I’m tracking quotes on licensed transport companies Honolulu and trying to lock in before rates change again.
Love your advice on fence preservation! For repairs, I have faith Additional resources utterly.
Exceptional particulars elaborated masking aesthetics whilst making certain security is still precedence sold incredible framework constructing expectancies around tasks undertaken even as attractive pros representing partnerships shaped due to br here
Valuable information — we had a great experience with google.com in New Albany.
Insurance riders for high-value items were easy once we used the template COIs from bald eagle west palm .
We map ad angles to landing page sections one-to-one. Blueprint here outsourced social media ads agency .
Insurance verification matters—get the carrier’s COI. I booked through car shipping companies New Orleans and the documentation was sent before pickup.
В этой публикации мы рассматриваем важную тему борьбы с зависимостями, включая алкогольную и наркотическую зависимости. Мы обсудим методы лечения, реабилитации и поддержку, которые могут помочь людям, столкнувшимся с этой проблемой. Читатели узнают о перспективах выздоровления и важности комплексного подхода.
Раскрыть тему полностью – [url=https://moimesyachnye.ru/reabilitatsiya-narkomanov-protsess-vosstanovleniya-i-novaya-zhizn.html]tver clinica plus[/url]
nottingham forest betting shops brighton (https://Basketball-Wetten.com/) odds
The graphics exhibiting earlier-and-after roof valleys had been certainly convincing. We use same examples whilst we dialogue to property owners at roofing company services about water leadership.
We had sagging gutters inflicting fascia rot; affordable roofing Millsboro DE in Millsboro repaired both effectively.
I manage several rental units in Los Angeles and durable, high-quality cabinetry is essential. I’m considering partnering with cabinet shop los angeles for a standard cabinet package across multiple units.
Georgetown’s narrow streets are no joke for moving trucks. We used a shuttle solution suggested by the movers we found via washington dc moving companies .
Этот информационный материал подробно освещает проблему наркозависимости, ее причины и последствия. Мы предлагаем информацию о методах лечения, профилактики и поддерживающих программах. Цель статьи — повысить осведомленность и продвигать идеи о необходимости борьбы с зависимостями.
Получить профессиональную консультацию – [url=https://osbplity.ru/lechenie-narkomanii-kompleksnyj-podhod-k-borbe-s-zavisimostyu/]лечение наркомании в Твери[/url]
This was highly useful. For more, visit envío de mochilas Camino de Santiago .
Very informative article. For similar content, visit เว็บหวยออนไลน์สมัครฟรี .
For insurance plan adjuster meetings, bring a roofing contractor Manassas Virginia. siding services met ours on-web site and documented hail affects.
After two failed programs, our son finally floats calmly; kudos to swim lessons coral gables for the patient instructors.
I found this very interesting. For more, visit servicios expertos extranjería .
Martial arts not just boost fitness however additionally instill discipline and focus in practitioners. It’s remarkable to see just how various styles, from martial arts to jiu-jitsu, deal unique benefits Denver Taekwondo
Этот обзор содержит информацию о передовых достижениях в области медицины. Мы разберем инновационные технологии, которые меняют подход к лечению и диагностике, а также их влияние на эффективность оказания медицинской помощи.
Информация доступна здесь – [url=https://clubsamodelok.ru/remont-tela-posle-prazdnikov-granicy-narodnyx-metodov-i-kogda-nuzhna-professionalnaya-pomoshh/]капельница от запоя на дому[/url]
В статье по вопросам здоровья мы рассматриваем актуальные проблемы, с которыми сталкивается общество. Обсуждаются заболевания, факторы риска и важные аспекты профилактики. Читатели получат полезные советы о том, как сохранить здоровье и улучшить качество жизни.
Получить профессиональную консультацию – [url=https://med-pro-ves.ru/zdorove/vazhnost-protsedury-vyvoda-iz-zapoya-na-domu]наркологическая клиника в твери[/url]
Very informative. I believe bulldog movers maryland for obvious rates and caliber carrier.
This was a wonderful post. Check out nutrióloga pediátrica cerca de mí for more.
For anyone worried about swim caps and goggles, swimming lessons for kids has a beginner gear guide that eased my concerns.
If you would like right kind starter strips and sealed edges, roofing service in Millsboro does it appropriate.
Этот документ охватывает важные аспекты медицинской науки, сосредотачиваясь на ключевых вопросах, касающихся здоровья населения. Мы рассматриваем свежие исследования, клинические рекомендации и лучшие практики, которые помогут улучшить качество лечения и профилактики заболеваний. Читатели получат возможность углубиться в различные медицинские дисциплины.
Только для своих – [url=https://gala-pm.ru/sovremennye-podhody-k-lecheniju-alkogolizma-i-pomoshh-pri-zapoe/]клиника плюс тверь[/url]
Matterport 3D + stills combo worked great for me: real estate photography spring tx .
Эта публикация обращает внимание на важность профилактики зависимостей. Мы обсудим, как осведомленность и образование могут помочь в предотвращении возникновения зависимости. Читатели смогут ознакомиться с полезными советами и ресурсами, которые способствуют здоровому образу жизни.
Кликни, не пожалеешь – [url=https://lifepeople.info/novosti/semejnyj-krizis-kak-soxranit-molodost-i-pomoch-muzhu-spravitsya-s-zavisimostyu/]вывести из запоя недорого на дому[/url]
Switching schools? Request transcripts early and confirm zoning changes before you sign a lease. We lined up our timeline around a mover we found on bald eagle movers .
Thanks for the air flow advice. Anyone in Manassas need to ask a roofing contractor Manassas Virginia approximately ridge vent concepts— siding services explains them effectively.
It is fascinating to read about the potential for stem cell banking, though I agree that we should keep expectations realistic. It feels like a big decision for expecting parents to make under pressure https://www.mediafire.com/file/kf2a8iig3hq144o/pdf-4924-171.pdf/file
В этой статье мы рассматриваем разрушительное влияние зависимости на жизнь человека. Обсуждаются аспекты, такие как здоровье, отношения и профессиональные достижения. Читатели узнают о необходимости обращения за помощью и о путях к восстановлению.
Узнать больше > – [url=https://aboutweeks.com/prakticheskoe-rukovodstvo-po-programme-reabilitacii-12-shagov-i-sovety-po-ejo-ispolzovaniju.html]клиника плюс тверь[/url]
Moving into a DC rowhouse means tight stairwells and narrow doors. Measure twice, move once. We booked pros via Washington DC movers and it made all the difference.
Πολύ χρήσιμες οι προτάσεις σας για τη βελτίωση των Μεταφράσεων. Αν κάποιος θέλει άμεση εφαρμογή όλων αυτών σε δικά του κείμενα, μπορεί να δοκιμάσει τις υπηρεσίες του τοπικές μεταφράσεις Θεσσαλονίκη .
Thanks for this guide. I almost signed with a contractor before realizing they lacked proper CIDB registration. It is such a huge risk-especially for commercial projects here. Your point about verifying their status is spot on Click here!
I loved my day in Gibraltar last year! If you go, make sure you take the cable car up to the Upper Rock Nature Reserve. The Barbary macaques are hilarious, but keep a tight grip on your sunglasses. They love to snatch shiny things right off your face https://www.4shared.com/office/DRWUm2Z2ku/pdf-34562-24642.html
I definitely notice a huge difference in my skin when I don’t get enough rest. My eyes get so puffy and I always end up with a breakout by the next morning. It is tough to put my phone away at night, but your tips on bedtime consistency are super helpful! https://www.mediafire.com/file/yzfvs5kew3d7dlh/pdf-91405-60377.pdf/file
The Red Team Mode is pretty useful for spotting blind spots, but I find it takes a bit of trial and error to get the right output. Does anyone have a preferred prompt structure to make the feedback feel more actionable? document intelligence scribe
After a grueling race weekend, I regularly drop 5 to 10 lbs in sweat. Recovery usually feels impossible by Sunday night. I’ve been looking into CBD, but I worry about the rules https://www.4shared.com/office/ZNyWsmuyge/pdf-26036-60013.html
Living in Peterborough really grew on me during my degree. Honestly, the train to London was a total lifesaver for weekend trips or catching shows when I needed a break from studying. It makes the city feel way more connected than you’d expect at first what to pack for uni room
It is fascinating to read about the potential of umbilical cord stem cells. The science behind banking is certainly evolving, but it is important for parents to stay grounded in the current limitations https://wiki-global.win/index.php/How_Does_HLA_Matching_Work_for_Cord_Blood_Compared_to_Bone_Marrow%3F
As someone who manages billing, this push makes me really nervous. We are already dealing with so much overhead, and the OIG finding that they get back $4.64 for every $1 spent on enforcement is going to put a massive target on our backs Medicaid beneficiary access issues
Great read. I totally agree that vetting a contractor is the hardest part. I recently had a bad experience where the variation charges kept creeping up-midway through the renovation, which blew my budget wide open quality control in office renovation
I’ve definitely noticed that if I don’t get a full eight hours, my skin breaks out almost instantly. It’s wild how much a few late nights can impact my complexion Get more information
I’ve been experimenting with Debate Mode during my brainstorming sessions, and it’s honestly been helpful for spotting flaws in my logic before I pitch ideas to my team automated strategy brief AI tool
Gibraltar offers such a unique stop on any Mediterranean cruise. I loved hiking up to the Upper Rock Nature Reserve for the incredible views https://high-wiki.win/index.php/Is_Gibraltar_More_About_Nature_or_City_Exploring%3F