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
}
Timelines slip when freight elevators are shared across tenants. We used MyProMovers DC to lock in elevator blocks and avoid overtime fees.
Συμφωνώ ότι η ποιότητα στις Μεταφράσεις κάνει τη διαφορά. Αν κάποιος ψάχνει επαγγελματίες μεταφραστές, το επικυρωμένες μεταφράσεις είναι μια πολύ καλή λύση.
Useful advice! For more, visit nutricionista en Saltillo recomendaciones .
Honestly, those 2am wakeups from my toddler have been absolutely killing my energy lately. I have been really curious about trying a CBD tincture, but I am still a bit hesitant about the quality out there CBD tincture for sleep
Fascinating discussion on personal credit’s position in right this moment’s larger-charge atmosphere internet
I really appreciate this honest post. Being a mom to two toddlers, I definitely struggle with that end-of-day brain fog. I started holding the tincture under my tongue for the full 60 seconds like you suggested, and it makes a huge difference CBD for racing thoughts at night
This is quite enlightening. Check out envío de mochilas Camino de Santiago for more.
I really appreciate you sharing this perspective. It is so hard to find time to wind down as a mom. I have tried CBD, but I always struggle to remember to hold it for that full 30 to 60 seconds under the tongue https://www.protopage.com/victoria.wright12#Bookmarks
Just completed a condo move downtown WPB; the movers I found via movers west palm beach protected my furniture and the building’s elevators perfectly.
Great insights on minimizing downtime during an office move in DC. For anyone planning a quick, compliance-friendly transition, I recommend checking Washington DC movers for tailored business moving support.
For thorough snapshot studies after inspections in Millsboro, local roofer Millsboro DE brought detailed documentation.
I fully grasp how you explained the symptoms of shingle granule loss. We see this always all through roof inspections at Gikas Roofing reviews , and householders hardly discover it early.
Этот текст представляет собой обзор свежих данных и исследований в области медицины. Он призван помочь читателям понять, как научные достижения влияют на лечение, диагностику и общее состояние системы здравоохранения.
Расширить кругозор по теме – [url=https://vsetemy.ru/zavisimost/vyvod-iz-zapoya-s-vyezdom-vracha-na-dom-protsess/]tver clinica plus[/url]
We had been debating re-roof vs overlay— roofer near me covers Manassas pros and cons.
Thanks for the clear breakdown. Find more at cuidado integral de mayores .
Don’t ship new furniture during rainy season without covered delivery; our vendor checklist from bald eagle movers saved a headache.
Swapping utilities in DC is easier if you line them up a week ahead—Pepco, DC Water, Washington Gas. For the actual move, Washington DC movers connected us with a great local team.
I was really impressed by how clearly this information was presented. It is not always easy to find such a well-organized and unbiased overview online, so I wanted to thank you for putting this together and making it so accessible to everyone reading.
Xxx video onlyfans sex video site
Запоя вывод в клинике Сочи: лечение алкогольной интоксикации, капельница, детоксикация, помощь нарколога на дому, кодирование и реабилитация.
Детальнее – [url=https://vivod-iz-zapoya-sochi24.ru/]вывод из запоя цена сочи[/url]
Parking is tight near Rosemary Square—factor in employee permits and guest validations; bald eagle movers has a handy guide.
В статье по вопросам здоровья мы рассматриваем актуальные проблемы, с которыми сталкивается общество. Обсуждаются заболевания, факторы риска и важные аспекты профилактики. Читатели получат полезные советы о том, как сохранить здоровье и улучшить качество жизни.
Ознакомиться с отчётом – [url=https://zbi.biz/article/narkolog-na-dom-v-tveri-operativnaja-i-nedorogaja-pomoshh-ot-kliniki-pljus/]clinica plus[/url]
Love the tip about creating a move command center. We paired that with an IT cutover checklist from mypromovers washington dc and our switchover was done over a single weekend.
Thanks for breaking down guaranty terms—my contractor from roof repair in Millsboro explained the similar features.
Στον χώρο του e‑trade, οι σωστές Μεταφράσεις των περιγραφών προϊόντων αυξάνουν τις πωλήσεις. Εμείς συνεργαστήκαμε με το μετάφραση αποδεικτικών σπουδών και είδαμε διαφορά στα conversion quotes.
Thanks for the helpful advice. Discover more at pasos extranjería España .
I wanted assist navigating a roof assurance transfer in Manassas— Five Stars Roof Replacement explained it nicely.
Thanks for the informative content. More at mejor nutricionista en Saltillo .
Thanks for the great content. More at servicio de traslados Camino .
Your suggestions about normal roof repairs might keep folk a good number of payment. At Gikas Roofing services , we see minor things turned into most important issues when they’re left unchecked.
The comment on speed and structuring flexibility incredibly resonates. Third Eye Capital’s skill to diligence, value, and shut right now is a competitive side when debtors want fact Visit Website
Appreciate the thorough insights. For more, visit personas dependientes o mayores a domicilio .
Привет всем!
Для продвижения сайта важны не только ссылки и тексты, но и качество самой площадки: логика страниц, релевантность запросам, удобство интерфейса, скорость и понятные коммерческие сигналы. Поэтому разработку лучше совмещать с SEO-планированием. Подробнее: интернет-магазин под ключ — https://volt-site.ru/uslugi/razrabotka-sajtov Это снижает риск переделок после запуска и помогает быстрее перейти к продвижению.
создание сайта цена недорого, создание ecommerce сайта, заказать seo продвижение быстро
услуги разработки сайтов цена, seo продвижение цена студия, рост заявок с сайта
Всего наилучшего и роста в топ!
I’ve definitely noticed that if I skimp on sleep, my breakouts flare up almost immediately. It’s wild how much my skin reflects my bedtime! I really struggle with being consistent on weekends though impacts of sleep restriction
Gibraltar is such a fantastic cruise stop! I visited the Upper Rock Nature Reserve last year and absolutely loved the views. Just a heads up for everyone visiting: keep your bags closed tight around the Barbary macaques https://romeo-wiki.win/index.php/What%E2%80%99s_the_Best_Way_to_Experience_Gibraltar%E2%80%99s_British_Vibe_on_a_Port_Day%3F
Banking cord blood is a complex decision for expecting parents. It really feels like there is so much to consider before the baby arrives https://station-wiki.win/index.php/Cord_Blood_vs_Bone_Marrow_Transplant:_What_Are_the_Real_Differences%3F
Finding a reliable fit out contractor in Malaysia is such a headache. I learned the hard way that you really need to keep a close eye on variation charges before signing anything. They always seem to creep up during the renovation-process get more info
I’ve been using CBD after track days because my body really takes a beating pulling 2 to 3 Gs in the corners. It helps take the edge off when I’m finally off the circuit https://blast-wiki.win/index.php/CBD_Tincture_vs._Gummies:_The_Reality_of_Recovery_on_the_Road
I’ve been using Suprmind to stress-test my project briefs lately, and the Red Team Mode is surprisingly effective at catching blind spots I hadn’t considered. It’s saved me quite a bit of time during the revision process. best AI for deep market insights
I’ve definitely noticed that if I don’t get enough sleep, my skin breaks out almost immediately. Puffy eyes are the biggest giveaway for me too! I’ve been trying to put my phone away an hour before bed and it really seems to help with my complexion https://pastelink.net/k7y8g3v0
Gibraltar is such a fun stop on any cruise. I visited the Upper Rock Nature Reserve last year and absolutely loved seeing the Barbary macaques. Just a heads up, keep your snacks hidden because those monkeys are clever thieves https://knoxuqsk688.cavandoragh.org/are-the-world-war-ii-tunnels-in-gibraltar-worth-visiting-a-cruise-expert-s-take
This is such a fascinating topic for expectant parents to consider. While the potential for long-term medical use is interesting, it is important to remember that these therapies are still evolving and not guaranteed hla typing for stem cell donors
This is such a helpful guide for my upcoming office renovation. I have heard so many horror stories about contractors who hide their variation charges until the very end- which ends up blowing the whole budget. I really want to avoid that stress https://telegra.ph/Fit-Out-Contractor-for-a-Law-Firm-What-Design-Style-Actually-Fits-06-13
Racing in this heat definitely takes a toll. I usually walk away with a 5 to 10 lb sweat loss after a long stint, and my muscles feel totally trashed. I’ve been looking into CBD to help with the inflammation https://juliussinterestinginsight.image-perth.org/what-does-a-500-mile-race-do-to-your-body-the-reality-behind-the-cockpit
Fiyat/performans değerlendirmesi yapmak isteyenlere not: Diyarbakır bayan escort net bilgiler veriyor, sürpriz maliyet yok, iletişim de çok saygılı.
I’ve been testing out the Red Team Mode for vetting my project strategies, and it’s surprisingly good at catching logical gaps I usually overlook topai.tools Suprmind
As a billing lead, seeing the push for more scrutiny is honestly pretty stressful. When the OIG claims a return of $4.64 for every dollar spent on oversight, you know they are going to come for us with a fine-toothed comb. We need to be proactive shell entity Medicaid billing
I loved stopping in Gibraltar on my cruise last year! Make sure you head straight to the Upper Rock Nature Reserve early to beat the crowds Visit the website
I definitely notice a huge difference in my complexion when I do not get enough rest. If I stay up late scrolling on my phone or have a drink before bed, I wake up with puffy eyes and new breakouts Take a look at the site here
It is fascinating to read about the potential of umbilical cord stem cell banking. While it is an interesting option for some families, it is important to remember that current medical applications are still evolving and not guaranteed https://fiona_west02.raindrop.page/bookmarks-71945506
This is such a helpful guide for anyone navigating the Malaysian fit-out scene. I completely agree about checking for valid CIDB registration first. It really helps filter out the less professional ones before you even get to the quotes gym fit out contractor Malaysia