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
}
We had fragile ceramics; Jersey City Mover’s packed them with double cushioning.
Just finished relocating and I wish I had found Tom’s River Mover’s sooner—Toms River moving company expertise really matters when timing is tight.
Stressed about moving in Decatur? Decatur full service movers lists licensed movers with clear reviews.
Fantastic advice on choosing a plumber! It’s crucial to find someone reliable. For more tips and tricks, visit plumber .
This guide to preparing for a junk removal appointment is exactly what I needed. Once I follow your steps, I’ll have junk removal handle the rest.
If anybody’s having situation having access to the ck444 login page in these days, try clearing your cache or via an incognito window. I’ve also bookmarked an exchange entry aspect the following: click here now in case the most portal is slow.
If your door shakes on the way up, check balance— garage door spring replacement does proper spring calibration.
Thanks for the great tips. Discover more at Military Divorce Lawyer .
Thanks for the detailed guidance. More at TLC Carpett Cleaning .
mostbet tətbiq endir azərbaycan [url=https://mostbet2015.help]https://mostbet2015.help[/url]
After seeking nitrous oxide cream chargers, I’ve officially ditched my outdated whipped cream means! Check out the distinction at Click for more info .
I like how you broke down what can and can’t go in a dumpster. For items I wasn’t sure about, junk removal provided junk removal in St Charles and guided me on disposal.
такой [url=https://xyeta.store/order/kick-prosmotry]дешевое продвижение РЅР° РєРёРєРµ xyeta store[/url]
Thanks for the helpful advice. Discover more at divorce mediation .
We combined decluttering with moving day— international relocation Cornelius even helped donate items locally.
This was very well put together. Discover more at Oaks Dental .
Сайт Kraken – лучшая торговая площадка в Darknet
Торговая площадка Kraken Onion – лучший магазин Даркнета, где есть почти любые позволяющие расслабиться препараты, фальшивые документы и деньги, можно заплатить за взлом сайтов и пробив информации.
[url=https://kra53.co]kraken сайт[/url].
Посетителям гарантирована максимальная конфиденциальность, а количество магазинов постоянно увеличивается.
Товары и услуги на сайте Kraken
В магазинах сервиса можно найти такие предложения:
• Большой ассортимент наркотиков – от марихуаны и стимуляторов до опиатов и психоделиков.
• Обналичка Биткоинов.
• Взломанные аккаунты VPN.
• Услуги хакеров.
• Разные виды документов.
• Банковские карты и симки.
• Фальшивые деньги – обычно – от 1000 до 5000 рублей.
• Приборы и устрйоства – от скрытых камер и жучков до флешек для взлома.
This was very beneficial. For more, visit Family Lawyer service .
Wsparcie fizjoterapeutyczne w Hime pozwoliło mi przejść przez okres najcięższych treningów bez kontuzji. Regularny drenaż limfatyczny i praca na powięzi w tym gabinecie to standard, którego szukałem w Wołominie Fizjoterapeuta Wołomin
My kitchen sounds like a reputable bakery due to the fact incorporatingthese marvelouscharging units into my regimen—the consequences dialogue volumes!!! ##### anyKeyord##### Click for source
Well done! Discover more at Applecross Dentst .
Great insights on the significance of commonly used termite inspection! Homeowners occasionally fail to see early warning signals like hole-sounding wooden, mud tubes alongside foundations, or discarded wings close to windowsills Source
pin-up to‘lov usullari Oʻzbekiston [url=pinup39174.help]pinup39174.help[/url]
Moving student stuff from Bristol to Manchester on a budget— flat movers Bristol helped me find small-load options with shared trucks.
mostbet crash hry [url=www.mostbet32570.help]mostbet crash hry[/url]
1win hesabım kilidləndi [url=https://1win64218.help]https://1win64218.help[/url]
mostbet este legal în Moldova [url=www.mostbet40596.help]www.mostbet40596.help[/url]
Appreciate the detailed information. For more, visit MMD Medical Professionals .
On his Impact as an Investor:
“G. Scott Paterson has consistently proven himself as one of the most such a lot ahead-wondering traders within the media and technology sectors useful reference
Appreciate the reminder not to store things on stairways. I cleared mine and had junk removal st charles do junk removal st charles for the extra boxes.
Поиск аддиктолога в Москве редко бывает случайным. Как правило, к такому специалисту обращаются тогда, когда зависимое поведение уже начинает заметно влиять на повседневную жизнь: повторяются эпизоды употребления, случаются срывы после попыток остановиться, накапливается напряжение в семье, ухудшается сон, усиливается тревожность, появляются долги, конфликты и ощущение утраты контроля над ситуацией. У одних проблема связана с алкоголем, у других — с наркотическими веществами, а у третьих — с игровой зависимостью, когда ставки, онлайн-казино или другие формы азартного поведения постепенно вытесняют работу, общение и привычный ритм жизни.
Получить дополнительные сведения – [url=http://msk-clinica-plus.ru/]консультация адиктолог[/url]
mostbet verifikasiya olmadan çıxarış olurmu [url=https://www.mostbet2015.help]https://www.mostbet2015.help[/url]
Who knew finding a good plumber could make such a difference? Shoutout to my local guys in O’Fallon IL! plumbing near me
Платная наркологическая клиника «НОВЫЙ НАРКОЛОГ» в Санкт-Петербурге предлагает помощь в комфортных условиях с акцентом на безопасность пациента. Врачи подбирают схему лечения с учётом состояния, анамнеза и сопутствующих рисков, проводят медицинскую стабилизацию и помогают выстроить план дальнейшего восстановления. Анонимность и профессионализм остаются приоритетом.
Выяснить больше – [url=https://new-narkolog.ru/stati/pav-vred-psihoaktivnyh-veshchestv.html]социальные последствия употребления пав[/url]
Great tips on maintaining plumbing systems! I always find that regular checks can prevent bigger issues down the line. Check out more insights at plumber near me .
If you’re ever near Breese IL, don’t miss out on their fantastic food options! More at google.com .
https://mikefromgidstats.substack.com/p/why-you-should-fade-the-hype-at-pfl
PFL Sioux Falls feels like a homecoming event for Logan Storley masked as a sanctioned pro fighting show.
به صورت جمعبندی
برای کاربرایی که در جستجو هستن
شرط بندی
مشغولن
این مرجع
به سادگی میتونه
کاربردی دربیاد
از سوی دیگر
سایتهایی مثل
پلتفرم enfejаronline
و
پلتفرم sibbet
در حال رشد هستن
در یک نگاه
جذاب بود
و
حتما دوباره
دوباره چکش میکنم
Visit my website :: سایت معروف ایرانی [Lila]
It’s great that you mentioned tenant cleanouts. As a landlord, I rely on services like junk removal st charles when tenants leave behind tons of junk.
What’s the best way to track an overseas shipment out of the Port Newark area if I’m based in the Bronx? Does Cheap movers Bronx provide real-time tracking?
mostbet oficiální odkaz [url=https://www.mostbet32570.help]mostbet oficiální odkaz[/url]
1win cashback faizləri [url=http://1win64218.help]1win cashback faizləri[/url]
http://marketingrabbits.com/
A empresa Marketingrabbits consolida-se como uma estrutura de confianca dedicada ao panorama nacional portugues, que oferece servicos de qualidade a quem procura resultados, com foco na transparencia e confianca. Veja a oferta completa atraves do link.
mostbet limita card [url=https://www.mostbet40596.help]https://www.mostbet40596.help[/url]
Excellent info on residential property damage prevention. best tree removal company in Acworth utilized trumping up to reduced arm or legs without harming our roof covering.
This was a great article. Check out Hiberina Bar for more.
Great tips! For more, visit Simple Dental Center .
This was very enlightening. For more, visit Injury Recovery & Wellness Center .
Well explained. Discover more at The Kerner Law Group .
This is very insightful. Check out Injury Recovery Center for more.