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
}
kostenlos wetten ohne einzahlung
Here is my web site … virtual basketball-wetten (Loretta)
This pricing breakdown is helpful! I’m curious about how the rolling five-hour window works in practice is claude max worth it
wettanbieter mit gratiswette
Also visit my page – Basketball Wetten Gerade Ungerade
It’s actually a cool and useful piece of info. I’m satisfied that you just shared this useful information with us.
Please stay us up to date like this. Thank you for sharing.
Awesome article! Discover more at divorce mediator near me .
This breakdown of Claude Max pricing is really helpful. One point I wish the article touched on more is how the rolling five-hour window works for usage limits Visit this page
Помогаем быстро перейти от консультации к конкретному плану: выезд, стационар или наблюдение.
Получить больше информации – [url=https://vyvod-iz-zapoya-v-lyubercah14-4.ru/]вывод из запоя клиника[/url]
Need help with ISPM-15 compliant pallets for a studio move from the Bronx to Berlin. Can Office moving companies Bronx arrange compliant packing materials?
Ищете надежный обмен криптовалюты? Посетите сайт https://exchangeburo.com/ – мы гарантируем высокое качество обслуживания и выгодные курсы обмена. У нас: быстрый обмен, полная конфиденциальность, безопасность и надежность и выгодные курсы обмена. Посетите сайт узнайте больше о нас и предлагаемых услугах.
найти это [url=https://vodkabet-vb.com]вотка бет[/url]
Thanks for breaking down the Claude Max pricing! One thing I’m curious about is how the rolling five-hour window for usage actually works in practice how claude rolling window works
Appreciate the comprehensive advice. For more, visit painting company .
Вывод из запоя — это медицинская процедура, направленная на снятие алкогольной интоксикации, очищение организма от продуктов распада этанола, стабилизацию физического и психического состояния пациента. Когда употребление алкоголя продолжается несколько дней, недели или месяцев, организм испытывает серьезные нагрузки: страдают печень, почки, сердце, сосудистая и нервная системы, ухудшается сон, появляется тревожность, агрессия, рвота, головные боли, потеря сил, дезориентация и риск белой горячки. В таком случае нужна не просто домашняя помощь, а профессиональная наркологическая помощь под контролем врача.
Углубиться в тему – [url=https://vyvod-iz-zapoya-v-novorossijske3.ru/]анонимный вывод из запоя в новороссийске[/url]
sportwetten tipps prognosen
Feel free to surf to my page … ncaa Basketball wetten
Really appreciate the deep dive into Claude Max pricing! One thing I’m curious about is how the rolling five-hour window impacts usage Claude Max annual discount
Thanks for the invaluable insights. Drivers curious about Chevy gross sales or service guidance can determine Chevrolet service .
Hi to every body, it’s my first pay a visit
of this blog; this website includes remarkable and really good
information for readers.
Thanks for the practical tips. More at catálogo de enfermedades reumatológicas .
ios naar snooker wedden tips formula 1
I like the focus on improving quality of life. Pain management should support both comfort and function. Pain Management Clinic in Denver
buchmacher pferderennen
my webpage … Wetten Basketball VerläNgerung
Распознать критическое состояние, требующее участия профессионалов, можно по характерным признакам. Если у близкого наблюдается расстройство сознания, неадекватное поведение или резкие скачки артериального давления, медлить больше нельзя. В таких случаях необходима экстренная помощь врача-психиатра, ведь длительное воздействие токсинов может закончиться отказом жизненно важных органов. Вызвать нарколога на дом в Москве и области нужно при первых же угрозах, не дожидаясь усугубления ситуации. Наши специалисты готовы провести лечение запоя и снятие ломки немедленно.
Получить дополнительную информацию – [url=https://narkolog-na-dom-v-lyubercah14-1.ru/]vyzov-vracha-narkologa-na-dom[/url]
beste tips snooker winnende wedden platformen
Слушайте кто кухню недавно заказывал Менеджеры врут про материалы То фасады кривые Короче, реальные ребята с цехом — заказ кухни спб под ключ Проект бесплатно В общем, там цены и каталог — кухни от производителя спб [url=https://kuhni-spb-lvk.ru]https://kuhni-spb-lvk.ru[/url] Не ведитесь на салоны-прокладки Сам мучался теперь делюсь
If you’ve been curious about Botox but unsure where to start, browsing Orange County providers on Ketamine Infusion Therapy Orange County is a great first step.
Your emphasis on roof integrity before installing Tesla solar was helpful. I’ll have Solar Energy Systems Provider Southern California inspect for any repairs first.
roulette casino en ligne de jeu d’argent (Corine) ligne aams
Gum disease is easy to ignore until symptoms get worse, so information like this is really useful. Ventura residents searching for treatment options can learn more through Ventura gum care .
Great insights on planning an office relocation. Businesses in Fresno can really benefit from working with experienced commercial movers who understand tight schedules and minimal downtime. Fresno apartment movers
viver De apostas online que dão dinheiro
ios sportweddenschappen
Feel free to visit my blog post: naar waar Wedden op Snooker
Online Casino Ab 30 Euro Cashlib mit 25 euro einzahlung
milenium bukmacher Konin obstawianie live
Very informative article. Doing a little research before booking car transport can make the entire process safer, easier, and more reliable. Los Angeles auto shippers
Люди подскажите Ситуация критическая Дети боятся заходить в комнату В диспансер тащить — последнее дело Короче, спасла только госпитализация — капельница от запоя в стационаре круглосуточно Врачи и медсёстры 24/7 В общем, вся инфа по ссылке — вывод из запоя в стационаре в нижнем новгороде [url=https://alkogolizm.vyvod-iz-zapoya-v-staczionare-nizhnij-novgorod-knd.ru]https://alkogolizm.vyvod-iz-zapoya-v-staczionare-nizhnij-novgorod-knd.ru[/url] Звоните прямо сейчас Перешлите тем кто в беде
For anyone in Southfield MI updating an older bathroom, I’ve seen great tile and fixture combinations on Asphalt Roof Installation Southfield MI that fit Midwest styles.
Thanks for the great tips. Discover more at apartamentos y casas rurales .
Congratulations! You are my saviour, and for millions. You are the best user friendly app. I would suggest this to million people a million times ever. Honestly this is the most best app for creators. And it’s the one and only app which have everything required for the creator in it ! Love this app to the core. I will definitely be the lifetime user. ❤️️ It’s easy to overlook pre-loaded apps like Apple’s own Clips but, with the weight of the tech giant’s best brains behind it, this video editing app has plenty of powerful features to admire. Take their live tiles setting as an example. This lets you create animated captions and titles that appear automatically as you speak. Turn your photos into meaningful stories. Create your own slideshows with text, effects, and music with Videoleap app. No video editing experience needed.
https://mapaalimentos.com/?p=138820
Vimeo is a highly professional text animation app with an extensive toolkit that ensures maximum text animation and video editing features. Despite its vast array of additional features, the app remains easy to use, even for beginners. As well as some basic edit features such as music and voiceover, the application enables multi-level personalization with its cut editing and clip-adjustment features. Some of the significant components of the app are: Top Animation Tool Animate your text in one click. Choose from hundreds of pre-made animation templates to add personality to your designs. See your static text come to life and captivate your audience. Online Video Maker Open the “Text” tab in the left sidebar and choose from 100+ text fonts or upload your own custom font. Then, open the “Animate” tab in the right sidebar and select the animation you want to add to your text.
Moving requires a lot of organization, and this post explains that well. For those looking for Durham moving help, Durham full service movers may be useful.
Any seasonal rate spikes for Durham routes? I’m tracking price changes on Durham enclosed car transport .
Ребята, всем привет! Фурнитуру подсовывают самую дешманскую и ненадежную. То демонстрационные фасады на стендах кривые до тех пор, не протестировал единственную фабрику, которая не наваривается на посредничестве с огромным выбором влагостойких материалов и качественной сборкой. Итоговые цены получились ниже розничных салонов минимум на 30%,
Кому тоже актуально обновить мебель на кухне без лишней переплаты, смотрите сами весь каталог фабрики по ссылке купить кухню в спб недорого от производителя [url=https://zakazat-kuhnyu-jep.ru]https://zakazat-kuhnyu-jep.ru[/url] Всегда заказывайте корпусную мебель напрямую у завода-изготовителя, обязательно перешлите этот пост тому, кто тоже сейчас ищет качественную мебель! Сам долго мучался, теперь делюсь проверенным местом.
Reusable animationsTest ideas quickly with built-in presets. Copy and paste animations across layers to move faster and stay on-brand. Have you ever wondered how to make a video animation in 2D with no video making background? Our 2D animation software templates do all the hard work for you, providing top-notch flat visuals. LottieFiles is an animation video app that lets you create, edit, and export Lottie animations with ease. It’s especially useful for UX designers and developers, offering a library of free animations and an editor to tweak colors or add backgrounds. You can even set animation triggers based on clicks, scrolls, or hovers—bringing your content to life. One of the most significant advantages of Krikey AI’s free animation maker is its cost-effectiveness. Krikey AI Animation Maker can be used by anyone, regardless of their past animation experience or coding experience. You can even make and save animated GIFs for free using the AI Animation generator.
https://electrogame.ro/uk-winner-casino-a-review-for-united-kingdom-players-2/
VITA – Video Editor & Maker The best video-editing software for Mac for beginners is one with a simple interface and useful tutorials that will help you get the first result quickly and with little effort. Movavi Video Editor, iMovie, and Adobe® Premiere® Elements have all the qualities of the above. They are the easiest Mac video editors to master and have everything you need to make videos. If you are just getting started, give one of them a try! Make text and stickers follow your subject’s movement seamlessly, or easily apply moving blur and mosaic effects to protect privacy in your videos. I edit on Macs. They’re designed for video, they come with the useful iMovie editing program, and they’re widely used in the film and media industry. You get more for your money with a PC, but they aren’t as user-friendly.
sites de apostas sao legais (Ryan) de apostas
com app
There’s nothing quite like delighting in a summer night on a properly designed backyard deck deck contractor
Great insights! Discover more at cuidados útiles mascotas .
Люди подскажите Отец не встаёт с кровати Родственники в полном отчаянии Скорая не приедет на такой вызов Короче, единственные кто взялся за безнадёжный случай — цена вывода из запоя в стационаре доступная Врачи и медсёстры 24/7 В общем, не потеряйте контакты — цена вывода из запоя в стационаре [url=https://alkogolizm.vyvod-iz-zapoya-v-staczionare-nizhnij-novgorod-knd.ru]цена вывода из запоя в стационаре[/url] Не ждите пока станет хуже Это может спасти жизнь
Рекомендации строятся вокруг состояния человека, а не по универсальному шаблону для всех случаев.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-v-lyubercah14.ru/]нарколог вывод из запоя[/url]
Appreciate the comprehensive advice. For more, visit traslados desde Santiago de Compostela al aeropuerto .
опубликовано здесь [url=https://vbt-vodkabe.com/]vodkabet[/url]
Don’t forget to reserve elevators in condo buildings around Western Branch. My mover coordinated it perfectly after I booked through cheap Chesapeake moving services .