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
}
Reply with: “Write 25 helpful blog comments for New Brunswick moving company” and I’ll generate them in the format you requested. residential apartment movers NB
Genuine outreach emails to local blogs. Jackson Township moving teams
Grateful for all these resources you’ve provided ; they’ll make finding quality care at north gate much easier than expected !! ##### any keywords ##### Northgate Injury Chiropractor
Thanks for the practical tips. More at guías clínicas reumatológicas .
Have you ever struggled with carpal tunnel syndrome? An ##Everett Chiropractor## might be able to help with that! Everett Car accident recovery
apostando o’que significa
My web-site :: melhores apostas hoje; Shanon,
video poker uitbetaling paysafecard
my web page … casino belgie 200 Gratis Spins
Helpful guidance for everyone searching out a trusted area to shop for a motor vehicle. GMC financing options gives you extra Buick GMC information.
Thanks for the valuable article. More at Urbina’s Painting Company San Jose .
Слушайте кто знает Брат снова сорвался Дети напуганы Нужна срочная помощь на дому Короче, единственное что вытащило из запоя — вывод из запоя с выездом врача Поставили капельницу с детоксикационным раствором В общем, жмите чтобы сохранить — вывод из запоя в спб недорого [url=https://narkolog.vyvod-iz-zapoya-na-domu-sankt-peterburg.ru]https://narkolog.vyvod-iz-zapoya-na-domu-sankt-peterburg.ru[/url] Не ждите пока станет хуже Перешлите тем кто в такой же ситуации
Clogged nozzles have been my nightmare; a clear out flush time table solved it. Maintenance record: sprinkler system install .
Love the element about seasonal ameliorations. I use ET-established scheduling and posted my monthly runtime chart right here: sprinkler system install .
Moving locally in Trenton is much easier when you find affordable movers with good service. Best Trenton movers is a nice resource to keep in mind.
It’s not just about physical help; in a small home, emotional support is built into everyday interactions like meal prep and walks. That’s a huge advantage I’ve seen discussed on assisted living near me .
Питер, всем привет Близкий человек уже несколько дней в запое Соседи стучат в стену Нужна срочная помощь на дому Короче, врачи приехали и поставили систему — вывод из запоя санкт Петербург недорого Поставили капельницу с детоксикационным раствором В общем, жмите чтобы сохранить — нетзависимости-вывод из запоя| нарколог на дом| кодирование санкт-петербург [url=https://narkolog.vyvod-iz-zapoya-na-domu-sankt-peterburg.ru]нетзависимости-вывод из запоя| нарколог на дом| кодирование санкт-петербург[/url] Не ждите пока станет хуже Перешлите тем кто в такой же ситуации
Thanks for explaining this matter in basic terms. Bail bond assist in Imperial County is additionally mandatory whilst time is constrained. Drug charge bail bonds
Blacklight inspection for pet urine is a big plus. Chose a provider offering it via St George Utah carpet cleaners .
Слушайте, кто реально сталкивался с такой бедой? Ситуация реально критическая, Родственники в панике и вообще не знают, что делать. Никакие народные методы и таблетки из аптеки вообще не помогают пока чисто случайно не наткнулся на экстренных наркологов с лицензией, начиная от качественной детоксикации на месте и заканчивая подбором медикаментов. Уже через пару часов человек наконец-то пришёл в себя и уснул,
В общем, если не хотите рисковать жизнью близкого человека, жмите на источник, чтобы случайно не потерять контакты капельница от похмелья купить [url=https://kruglosutochno-chastnyy.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru]капельница от похмелья купить[/url] Не ждите, пока состояние станет еще хуже, обязательно перешлите этот пост тем, кто тоже сейчас находится в такой же критической ситуации!
This program facilitates precise control over video speeds. Users can adjust the duration of each frame, whether speeding up or slowing down playback rates. By modifying the stroke length, you can drastically change how quickly or slowly a video plays. The ability to convert videos to MP4 files also signifies that this app allows efficient sharing capabilities among users. Furthermore, it streamlines the processes of transformation and management to ensure everything fits everyone’s needs perfectly. KineMaster is a versatile free video editor, well-suited for professional editors. KineMaster provides advanced features, enabling the creation of high-quality videos and slideshows complete with sound effects. InShot is also a photo editor and collage maker. Edit pictures and selfie, remove bg, add filters, adjust HSL, etc. Make stylish Instagram story covers and posts.
http://wp-danmark.dk/forum/profile/moichenrowill1988
Storyboarding is key to tell your story the best way. In this class you will learn everything about types of shots, camera movement, and composition rules,… before we make a complete storyboard and animatic together. After Animate is one of the most versatile and a really good animation app available. You can use it to design vector graphics and interactive animations for websites, banner ads, movie animations, animated GIFs, and virtually any sequence of moving images you can imagine. Rive combines an interactive design tool, a new stateful graphics format, a lightweight multi-platform runtime, and a blazing-fast vector renderer. What is 2D animation? 2D animation is without a shadow of a doubt the cornerstone of visual storytelling. For many years, it has captivated audiences with its ability to bring characters and narratives to life through dynamic visualization and creative storytelling. The art form seamlessly combines artistic creativity with technical expertise, making it an attractive field for aspiring artists looking to explore their potential. We’ve written a guide to demystifying the intricacies of 2D animation. This guide was a great, fun, and interesting adventure for us! Take a look at our insights and practical advice. This article will be especially useful for those who are just starting out in animation.
Personalized bathing schedules, preferred hygiene products, and familiar routines are easier to honor in a small home setting. That kind of individual attention is what drew me to assisted living amarillo tx .
Помощь оказывают врачи с практикой в наркологии, психиатрии и восстановительной терапии.
Получить больше информации – [url=https://narkolog-na-dom-v-lyubercah14-1.ru/]вызов нарколога на дом[/url]
Вывод из запоя в Королеве требуется, когда человек несколько дней употребляет алкоголь, не может остановиться, плохо спит, испытывает тревогу, тошноту, тремор, слабость, потерю аппетита и признаки похмельного синдрома. В такой момент главное — не пытаться лечить запойное состояние случайной дозой лекарственных средств, а обратиться к врачу. Наркологическая клиника подбирает лечение индивидуально: учитываются возраст пациента, срок употребления спиртного, стаж алкоголизма, наличие хронических заболеваний, самочувствие, риск развития осложнений и желание больного начать путь к трезвости.
Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-v-koroleve14.ru/]королев вывод из запоя[/url]
Здорова, народ Близкий человек уже две недели в запое Соседи уже вызвали участкового Платная клиника просит бешеные деньги Короче, единственные кто взялся за безнадёжный случай — вывод из запоя в стационаре с интенсивной терапией Выписали через неделю здоровым В общем, не потеряйте контакты — вывод из запоя в клинике самара [url=https://lechenie.vyvod-iz-zapoya-v-stacionare-samara12.ru]https://lechenie.vyvod-iz-zapoya-v-stacionare-samara12.ru[/url] Звоните прямо сейчас Перешлите тем кто в беде
Many families underestimate how tiring daily tasks can become with age. The focused help available in small homes, like those on respite care , can greatly reduce stress for both seniors and caregivers.
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 moving companies
I didn’t know that some Assisted Living communities now offer memory care units, while Nursing Homes traditionally handle more advanced medical issues. I first read about this evolving model on senior care during my research.
find more info https://web-samourai.com
Быстро собираем первичную информацию, оцениваем риски и предлагаем подходящий вариант обращения.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-v-koroleve14-1.ru/]vyvod-iz-zapoya-korolev[/url]
You can play Bigger Bass Bonanza from just 12p per spin. You can check out all the latest Big Bass Bonanza Megaways and other slot machine offers in our special offer & bonus promotion page. Beyond Big Bass Bonanza, you should also have plenty of options to play slots. The casino you choose must have a diverse collection of non GamStop slots of all types. Therefore, we picked out casinos that have a good slots library including titles from the leading software providers. We also looked for variety so players can enjoy different types of slots such as traditional slots, video slots, progressive slots, etc. In our Sky Vegas Casino review, we talk about this leading UK casino that’s renowned for its vast slot collection, including the Big Bass Series, which is available in demo mode for free play. Licensed by the UK Gambling Commission, Sky Vegas ensures a secure and fair gaming environment.
https://nikadress.ir/maneki-casino-review-maneki-slots-payout-rates-analysed-for-uk-players/
If you’re searching for a free alternative to CapCut, Meitu might be the perfect choice. While Meitu is best known as a photo editing app, it also offers video editing tools. Its beauty filters and facial enhancement features make it a favourite for selfies and portraits. Unlike CapCut, which focuses on video editing, Meitu excels in image enhancements but still provides creative tools for videos. Whether you’re a beginner or an expert, Meitu’s user-friendly interface ensures a smooth editing experience. The platform stays abreast of the latest trends by incorporating contemporary effects, ensuring that users’ creations are both modern and engaging. Additionally, CapCut enhances the overall quality of images by improving resolution and enriching color profiles. For users seeking more advanced capabilities, CapCut Pro provides exclusive access to premium effects, seamless transitions, professionally designed video templates, and an innovative auto cutout feature, all aimed at elevating the production value of any project.
nieuw Bonus tot 20 euro casino almelo
Информация об обращении не передается третьим лицам, а детали лечения обсуждаются только с пациентом.
Подробнее тут – [url=https://vyvod-iz-zapoya-v-koroleve14-2.ru/]vyvod-iz-zapoya[/url]
Loved that you encouraged multiple visits with different family members. I’ll reference this idea in my planning articles on senior care .
nfl tips idag
my web-site – Snabb utbetalning paypal betting
Planning ahead makes apartment moves much easier. If you’re relocating in Toledo, Toledo commercial movers can help you explore moving support.
premium roulette casino
My site – bingo betalen met ideal [Horacio]
I too can help with: look at this site
Слушайте кто знает Брат потерял человеческий облик Родственники в полном отчаянии Платная клиника просит бешеные деньги Короче, единственные кто взялся за безнадёжный случай — вывод из запоя самара стационар с палатой Капельницы и уколы по схеме В общем, не потеряйте контакты — вывести из запоя в стационаре [url=https://lechenie.vyvod-iz-zapoya-v-stacionare-samara12.ru]вывести из запоя в стационаре[/url] Стационар — это единственный выход Это может спасти жизнь
Visual schedules reduce anxiety and improve cooperation at home. albuquerque home care
My aunt downsized in Berry Hill and we got a cheap, careful moving crew using best movers in Mansfield .
Great points about vehicle transport in the St. Louis area. Many customers forget to confirm pickup and delivery details in advance, which can avoid delays. St. Louis car shippers can help make the process easier.
hoogste verjaardagsbonus Beste casino Korting
It’s really a great and helpful piece of info. I
am happy that you shared this helpful information with us.
Please keep us up to date like this. Thanks for sharing.
my web-site University of AlMaarif
I locked my keys in the car last month— mobile locksmith saved the day in under 20 minutes.
ishockey speltips
Here is my web site spel utan spelpaus paypal (https://www.jenniferhope.com/)
Слушайте, кто реально сталкивался с такой бедой? Брат снова жестко сорвался после долгого перерыва, Родственники в панике и вообще не знают, что делать. В обычную государственную больницу тащить человека просто страшно до тех пор, не наткнулся на экстренных наркологов с лицензией, начиная от качественной детоксикации на месте и заканчивая подбором медикаментов. Полностью сняли мучительную ломку и стабилизировали общее состояние.
Кому тоже экстренно необходим проверенный круглосуточный телефон наркологии, вся полезная инфа выложена вот здесь капельница при алкогольной интоксикации цена [url=https://kruglosutochno-chastnyy.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru]капельница при алкогольной интоксикации цена[/url] Не ждите, пока состояние станет еще хуже, обязательно перешлите этот пост тем, кто тоже сейчас находится в такой же критической ситуации!
It’s great that you covered both comfort and long-term savings. central heating and air conditioning doylestown
Useful advice! For more, visit información práctica mascotas .
If your team is preparing for an office move in Alameda, choosing experienced movers can help everything stay on track. More information is available here: moving companies in Alameda
Preventive plumbing maintenance is so important, especially in older homes around Southampton, PA. plumber southampton pa seems like a helpful option.
app de apostas esportivas
Check out my web-site; melhores times para apostar em gols