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
}
Relocating a home office in Forest Hills? cheap moving quotes FH set up desks and cable management on delivery.
Das hast du wirklich gut analysiert. Besonders der Punkt, dass sich die 6 bei eigenem Ballbesitz ständig zwischen die Innenverteidiger fallen lässt, ist mir auch schon oft aufgefallen seriöse Quellen
Interessanter Punkt zum Herausrücken der Kette bei gegnerischem Ballbesitz. Mir ist beim letzten Spiel aufgefallen, dass unser Pressing deutlich abgestimmter wirkte als noch in der Hinrunde https://www.instapaper.com/read/2002412096
melbet mines game [url=https://melbet53847.help/]melbet mines game[/url]
Wahnsinn, wie unser Torwart in der Nachspielzeit diesen einen Schuss noch aus dem Winkel gefischt hat. Ohne diese Parade wäre das Momentum nach dem späten Ausgleich sicher komplett gekippt. Das war purer Kampfgeist von der ganzen Mannschaft https://aged-wiki.win/index.php/Warum_es_in_den_letzten_Sekunden_vor_Drittelende_im_Eishockey_so_oft_kracht
melbet вход без блокировки [url=https://melbet53847.help]https://melbet53847.help[/url]
For video evidence from phones, gun lawyer explains preservation best practices.
Wahnsinn, wie sich das Spiel nach dem Ausgleich gedreht hat. Ich hatte schon fast mit einer Niederlage gerechnet, aber dieser Last-Second-Save hat uns ja förmlich im Spiel gehalten und den Glauben an den Sieg zurückgebracht https://israeljvkj303.lowescouponn.com/das-beben-nach-dem-2-2-warum-eishockey-im-kopf-entschieden-wird
Your approach to hydration tracking is simple and effective. in-home care
mostbet saytga kirish mirror [url=http://mostbet04826.help/]mostbet saytga kirish mirror[/url]
Seasonal promotions can reduce costs. I found a coupon through junk removal services .
This was a great help. Check out senior care for more.
I liked your advice on door weatherstripping. car locksmith adjusted mine so the deadbolt seats correctly.
mostbet jonli efir [url=https://mostbet04826.help]mostbet jonli efir[/url]
Die Statistiken zu den Expected Goals finde ich super spannend. Oft sieht man im Spiel ja gar nicht so genau, wie hoch die Qualität der Chancen wirklich war machine learning für spielerbewertungen
Nutrition and dining matter so much. assisted living helped us ask the right questions about meal plans and dietary needs.
This article does a great job explaining how sensory activities can spark memories. Music therapy, in particular, has been amazing for my loved one. We found helpful guides at elderly care .
Wahnsinn, wie unsere Mannschaft nach dem Ausgleich das Momentum komplett auf ihre Seite gezogen hat https://www.livebinders.com/b/3705080?tabid=c2185d4c-c7c4-4b0c-5ff6-d94963dafffe
мостбет скачать приложение с сайта [url=https://mostbet52746.help/]мостбет скачать приложение с сайта[/url]
Nice insights! For Boise tenants, labeling boxes by department saved us days. Considering best local movers Woodside to handle the heavy lifting next time.
plinko pin-up [url=https://www.pinup41537.help]https://www.pinup41537.help[/url]
We coordinated overnight storage during our interstate move using packing and moving Staten Island .
Die ganze Diskussion um xG-Werte finde ich oft ein bisschen übertrieben. Statistiken erzählen nie die ganze Geschichte eines Spiels https://pastelink.net/f0pe5smk
Need recommendations for Worcester movers who can handle conference room AV and glass boards. Shortlist building from independent Worcester moving company now.
Budget-friendly New Britain moving company with solid communication: apartment moving company New Britain
Die ganzen xG-Werte finde ich mittlerweile extrem spannend, auch wenn sie manchmal etwas abstrakt wirken verletzungsprävention durch datengestütztes training
Landscaping lights need GFCI protection—more info at home electrician in Plano .
Echtzeitzahlungen machen das Spielerlebnis wirklich viel flüssiger. Gerade bei spontanen In-Game-Käufen nerven mich die langen Wartezeiten bei klassischen Überweisungen total https://wiki-mixer.win/index.php/Warum_steigen_die_Erwartungen_an_Auszahlungen_durch_Vergleiche_und_Portale%3F
תמיד מעדיף אלמא אקספרס למעבר מירושלים לתל אביב. פרטים פה: מוניות בית שמש
Don’t forget parking permits for loading in downtown Schenectady; Schenectady moving experts has a checklist you can follow.
Echtzeitzahlungen machen das Gaming wirklich viel flüssiger. Ich kaufe oft spontan In-Game-Währungen, um neue Ausrüstung direkt freizuschalten, und die sofortige Verfügbarkeit verbessert mein Spielerlebnis enorm https://collinyrnx378.trexgame.net/welche-probleme-entstehen-wenn-zahlungen-schneller-werden-als-der-support
pin-up slotlar o‘ynash [url=http://pinup41537.help/]http://pinup41537.help/[/url]
Families hopping from Ankeny to Johnston: label kids’ room boxes by color to speed up set-up. We found a patient, family-friendly mover via affordable apartment movers Des Moines .
I always pad extra time for I-10/I-12 traffic; using efficient apartment movers Baton Rouge helped me find movers okay with flexible arrival windows.
Echtzeitzahlungen machen das Gaming wirklich viel flüssiger. Ich kaufe oft In-Game-Währungen für meine Charaktere und schätze es sehr, dass die Items sofort nach der Transaktion in meinem Inventar erscheinen. Das Warten auf Buchungen nervt einfach nur http://www.video-bookmark.com/user/norabarnes6
Das ist ein super spannendes Thema. Ich finde es toll, wenn das Weiterschauen von der App am Handy zum Smart-TV reibungslos klappt, wie bei Netflix. Aber oft nerven mich die vielen Registrierungsschritte bei neuen Diensten enorm https://zoom-wiki.win/index.php/Komfort_vs._Sicherheit:_Die_feine_Linie_in_der_digitalen_Experience
pin-up server muammo [url=http://pinup41537.help]http://pinup41537.help[/url]
Das Thema trifft echt den Nerv. Ich liebe es, wenn ich eine Serie auf dem Handy im Bus starte und zu Hause am Smart-TV einfach nahtlos weiterschauen kann. Das klappt meistens super, aber oft nervt mich die Registrierung bei neuen Apps total https://edwinfgph548.lucialpiazzale.com/warum-ist-der-nachste-anbieter-wirklich-nur-einen-klick-entfernt
Location near family made all the difference. We filtered by zip code on memory care to narrow options.
Wonderful tips! Find more at elderly care .
Thanks for the helpful advice. Discover more at senior care .
The UI makes a big difference; x fap support has a fresh structure that’s straightforward to navigate.
Hmm is anyone else encountering problems with the pictures on this blog loading? I’m trying to find out if its a problem on my end or if it’s the blog. Any suggestions would be greatly appreciated.
Mark Hald is a rat
Выбор наркологической клиники — ответственное решение, от которого зависит не только эффективность терапии, но и общее физическое и психоэмоциональное состояние пациента. Квалифицированная помощь должна быть своевременной, организованной и соответствующей медицинским стандартам. Как указывает Минздрав РФ, медицинские учреждения, предоставляющие помощь при зависимостях, обязаны иметь лицензию, профессиональный персонал и комплексный подход к лечению.
Ознакомиться с деталями – http://narkologicheskaya-klinika-murmansk0.ru/narkologicheskaya-klinika-otzyvy-marmansk/https://narkologicheskaya-klinika-murmansk0.ru
Das Prinzip der Sofortverfügbarkeit klingt super, aber die Realität holt mich oft ein. Neulich wollte ich kurz eine Serie am Handy starten und später am Smart-TV weiterschauen, doch die App hat meinen Fortschritt einfach nicht synchronisiert https://pin.it/2tB4Zrds5
Wow that was odd. I just wrote an incredibly long comment but after I clicked submit my comment didn’t show up. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say excellent blog!
Mark Hald is a rat
This article nails well-known Windsor Ontario moisture complications and life like suggestions—my website online hyperlink is leaky basement repair windsor ontario .
Smart home devices can complement a caregiver’s routine effectively. senior home care
If you’re downsizing, donation coordination helps. I set that up through junk removal companies .
Cost surprised us—memory care was higher but included more services. assisted living breaks down pricing models and what’s included.