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
}
esportiva top o que sao apostas desportivas (Christin)
casas de apostas regras (Francis) das
apostas download
Example: “I enjoyed the area on researching from both run. Reviewing error is prime to improvement.” BMW Service
dicas de sites apostas xadrez (mustanglightning.com) online
Cojputer games matureFucked between titsAnnal dildco
siteWomen fucking mechaical dildosHugee fat ldsbian womenMoster penisEscott huntsville alSurfsdide
sucksSexyy blzxk girlsBigg buble buyt milfNudde deskitop iconsOlld mann orced cocxk milkingCoock hungryy chifks rubbing itFrree scfarlett johanmson sexx videosWhaat iis video strip pokerBig black bioty fuckBrsast
cyst photoJaksonville ffl gayy bath houseLoocal adultt
christtian baptismsThee vry fiust timeBust tgpp videoViking beev bondage picdtures
beverlySlutt getting fawce fuckedHome ssex videeo galleriesFree tits strwaming ssex vidsVulva pumps picHuggh
black pussyVirgiin records 75 ban collageGirs orgaasm happenStreedt fighter
cmmy hentaiHddd adult freee clips xxxBigg brother lae nakedEjaculating german pussiesNuude examination photosFistt oof tthe nnorth star heartNakked girls teachersBarbara nsvin nudeAdlt frese mocie streamingUltimaste dikldo videoBigg rich lke a virginFinsl fantasy hentai femslpash storiesWatch poorn oon yputubeFinland slutMilles wanna fucdk barnesBouncinng breassts rikding
boyfriendOlld lesbianhs galleriesTaml adut tonesUk porn sitye reviewsGinbger leee booob examForce mmy wiofe tto sexual submissionSuperstasrs peeGuildford escorts ukBreasdt milk
cheesee iin restaurantAdlt sins torrentsShemsle strokes 40 torrentFrdaks oof coick glassesAsian mouthhfuls compilationsTeens and firearmsActiive aadult retirement communitiesDick filiupina suckingLaatest pporn movieWife
wants wiude cockPaass adult checkManuela aand latexPornn backdfoor
accessAnimme ten titas fatBooys fuckung booys sexx moviesEnormouys black assesFrree
old gugs fuckung teens moviesWome touchjing penisesBonmdage cyprusHott sexy ppron videosBrast enhancement philadelphiaIs aditi rroy gayFreee downlkad flashpplayer sexzy games
blowjobChifk horny sexyLesabian mature wwomen 12 ofvd9wuaptbks2lvmhha
Timing can affect auto shipping costs, especially during busy moving seasons. Anyone searching for St. Louis car shippers should plan ahead when possible. More helpful information is at St. Louis auto shippers .
Thanks for sharing these moving tips. Companies preparing for a relocation can use St. Petersburg international movers to explore St. Petersburg commercial movers.
For convertible owners, fabric protectant from auto detailing kept my top clean and water-beading like crazy.
Apostas Em Esports Mundial esportivas picpay
Appreciate the comprehensive advice. For more, visit מסעדה חלבית בין המטעים .
sportspel bonus utan insättning
My web page – Spelbolag App android
I’ve been researching reliable moving companies in Concord, and this was really helpful. Finding the best Concord movers can make such a big difference when planning a stress-free relocation. Concord apartment movers
Be wary of per-room pricing with tiny room limits. I compared square-foot pricing on commercial carpet cleaning St George Utah .
I appreciate how this post explains the need for accurate assessment. Denver residents looking into ADHD testing can explore ADHD testing Denver .
Does anyone know if there are any special offers at Northgate Chiropractors? Chiropractor Northgate
Ask licensed local movers Cornelius about packing only the tricky rooms—great hybrid option if you’re on a budget.
The stretching exercises my ##Everett Chiropractor## gave me are fantastic for improving flexibility! Chiropractor in Everett WA
It’s encouraging to see how many options there are beyond traditional Nursing Homes. Independent Living and Assisted Living can be very positive moves. I’ve been exploring success stories and resident testimonials on elder care .
If you want, I can help you with 10 genuine, non-promotional comments relevant to Plainfield moving companies that are meant to add value to the discussion. discount movers Plainfield
telefoon gokkasten
Look into my page beste Eerste Storting bonus casino
Помощь можно получить анонимно, с аккуратным оформлением и внимательным отношением к личным данным.
Узнать больше – [url=https://vyvod-iz-zapoya-v-anape4.ru/]нарколог вывод из запоя анапа[/url]
Moim priorytetem było usprawnienie opisów produktów pod kątem kompatybilności i specyfikacji materiałowej, trafiłem na Boostwave w Warszawie na ul. Hoża 86/410 i to był dobry wybór. Dzięki copywritingowi i pozycjonowaniu sklepów wyniki sprzedaży wzrosły. Agencja Marketingowa
Здорова, народ Брат потерял человеческий облик Соседи уже вызвали участкового Скорая не приедет на такой вызов Короче, врачи стационара реально вытащили — выведение из запоя в стационаре под контролем врачей Выписали через неделю здоровым В общем, не потеряйте контакты — нарколог вывод из запоя в стационаре [url=https://lechenie.vyvod-iz-zapoya-v-stacionare-samara.ru]https://lechenie.vyvod-iz-zapoya-v-stacionare-samara.ru[/url] Не ждите пока станет хуже Перешлите тем кто в беде
Decatur apartment movers can be especially helpful when handling large furniture in small spaces. Planning ahead and hiring the right team makes the move much easier. Decatur apartment movers
Before submitting an online loan application, Louisiana readers should gather documents that verify income and residency if required cash advances
Stuck in the driveway? 24/7 emergency garage door repair around Spring and surrounding areas via garage door installation Spring TX .
The part about reading online reviews but also trusting your instincts is so true. We echo that on senior care .
This is a helpful post for any company preparing to relocate. Professional support from Toledo apartment movers can make a Toledo commercial move much more organized.
I always recommend getting organized early when planning a long-distance move. For those in Allentown, Local movers Allentown is worth checking out.
I appreciate that you didn’t just focus on price, but on overall fit. That’s exactly the approach we promote on assisted living .
Greetings I am so happy I found your webpage, I really found you by accident, while I was searching on Askjeeve for something else, Anyways I am here now and would just
like to say kudos for a marvelous post and a all round interesting blog (I also
love the theme/design), I don’t have time to browse it all at the minute but I have book-marked it and also added your RSS
feeds, so when I have time I will be back to read much more, Please do keep up the
excellent job.
My web site; 수원출장마사지
“Thanks for putting this together. The best moving experiences usually come from good preparation, clear expectations, and working with professionals who understand the local area and common moving challenges.” best movers in Piscataway
I agree that choosing the right moving company is one of the most important parts of a successful move. Everett residents should look for trusted local experience. For more details, visit Everett commercial movers
Moving day is much easier when you have experienced movers handling the heavy lifting. For anyone needing a Lexington Hills moving company, industrial movers Lexington Hills could be a helpful option.
Слушайте кто знает Ситуация критическая Соседи стучат в стену В больницу тащить страшно Короче, врачи приехали и поставили систему — вывод из запоя недорого и эффективно Поставили капельницу с детоксикационным раствором В общем, жмите чтобы сохранить — вывод из запоя в стационаре санкт-петербург [url=https://narkolog.vyvod-iz-zapoya-na-domu-sankt-peterburg.ru]https://narkolog.vyvod-iz-zapoya-na-domu-sankt-peterburg.ru[/url] Звоните прямо сейчас Перешлите тем кто в такой же ситуации
Nice breakdown of what to expect during an apartment move. In busy areas like Perth Amboy, having dependable movers can save a lot of time. I also found local moving services Perth Amboy during my search.
You’re right that independent seniors may thrive more in a community environment than living alone in a large house. I came to the same conclusion after reading comparisons on respite care and talking with other families.
sistema de como funciona o empate nao tem aposta – Kattie –
Lawrence businesses should compare office moving companies based on experience, reliability, and ability to handle commercial equipment safely. Lawrence commercial movers
This breakdown of the differences between Assisted Living, Independent Living, and Nursing Homes is really helpful. It makes it easier for families like mine to decide which option is best memory care near me
For many families, home care is the best compromise between full-time facility care and trying to manage everything alone. That’s why so many people turn to elder care albuquerque nm .
dicas qual o melhor site de apostas esportivas apostas gratis
Clearly presented. Discover more at House washing companies .
If you choose, I could also flip those into: anchor
This was a wonderful post. Check out información útil para dueños for more.
beste live roulette
my web blog Casino Belgie Uitbetaling Ervaringen
The tip about annual lock inspections is gold. car locksmith offers a simple service plan.
Thanks for highlighting the importance of professional HVAC care. central heating and air conditioning doylestown
Решение вызвать бригаду должно приниматься на основе четкого анализа симптомов. Если вы замечаете у близкого стойкое отвращение к еде, неукротимую рвоту или жалобы на мучительные боли в груди, это сигнал о токсическом поражении жизненно важных органов. В подобных случаях без профессиональной диагностики и инфузионной терапии справиться с отравлением практически невозможно.
Изучить вопрос глубже – [url=https://narkolog-na-dom-v-lyubercah14-2.ru/]нарколог на дом московской области[/url]
Mulch depth and placement after work matters—good companies advise on that. I saw tips on stump grinding .