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
}
I used to blindly stack vitamins and CBD without thinking twice, but this really opened my eyes. Now, I always make it a point to check the NHS website for potential contraindications before adding anything new to my daily routine https://atavi.com/share/xviov4zvy18f
Solid advice about licensing and insurance. Before hiring new jersey roofing contractors, verify credentials and evaluations—here’s wherein I discovered transparent info: https://search.google.com/local/writereview?placeid=ChIJ6yS7W1mvw4kR1dA-InUppCA .
I used to buy into whatever influencers were pushing, but I got so confused by the mixed messages. Now, I always check the ingredient labels and look for third-party testing or advice from credible sources like the NHS. It makes such a difference Browse around this site
Stroller-friendly walks for recovering pups are available—details on Durham, NC dog walker .
It’s wild how much our wellness habits have shifted lately. Personally, relying on NHS as a trusted source has saved me from going down endless rabbit holes of misinformation online. It feels so much more reliable than just guessing what’s wrong telehealth vs in-person doctor visit
I really appreciate this perspective on tailoring routines to our actual lifestyles. Honestly, the desk-job tension in my shoulders is so real by the end of the day https://list-wiki.win/index.php/Is_It_Normal_to_Buy_Skincare_for_Stress_Relief%3F
Dizi finali bölündürecek türden; teoriler ve açık uçlar burada: Diyarbakır escort reviews
В данной статье рассматриваются физиологические и эмоциональные аспекты зависимости. Мы обсудим, как организм реагирует на зависимое поведение, и какие методы помогают восстановить здоровье и внутреннее равновесие.
Ознакомиться с деталями – [url=https://medixgroup.ru/oborudovanie-dlya-vyezdnoj-narkologicheskoj-pomoshchi/]вызов нарколога на дом[/url]
I’ve definitely felt overwhelmed by influencer marketing lately. It’s hard to know what’s legitimate when everyone is promoting the next big thing. I’ve started ignoring the hype and digging into ingredient lists and NHS guidelines instead https://angelowlnv711.yousher.com/how-to-stop-impulse-buying-wellness-products-a-skeptic-s-guide
LUCKY88 được xây dựng như một nền tảng nội dung trực tuyến với cấu trúc rõ ràng, giúp người truy cập dễ dàng khám phá các chuyên mục như thể thao, nổ hũ, bắn cá và đá gà bbc
I really enjoyed reading this perspective. I have dealt with serious fragrance irritation for years, so it is refreshing to see a focus on gentle, personalized habits instead of just chasing the latest trends https://griffinyoot346.raidersfanteamshop.com/what-should-i-do-when-a-viral-product-irritates-my-skin-a-wellness-editor-s-guide
I’ve definitely noticed a shift in how I research health topics lately. It’s wild how much more accessible everything is now, especially with the surge of TikTok burnout videos helping people name what they’re feeling https://tr.ee/-fS3zQ1ibN
Thanks for the great explanation. More info at ungüentos naturales con caléndula .
В этой статье мы рассматриваем разрушительное влияние зависимости на жизнь человека. Обсуждаются аспекты, такие как здоровье, отношения и профессиональные достижения. Читатели узнают о необходимости обращения за помощью и о путях к восстановлению.
Открой скрытое – [url=https://malyshok-m.ru/article/kapelnitsa-posle-zapoya-odin-iz-sposobov-borby-s-alkogolnoj-zavisimostyu]tver clinica plus[/url]
I have spent so much time being confused by wellness influencers making wild claims. It is refreshing to see a focus on real ingredients and testing. I have started checking the NHS website instead of taking advice from social media best wellness products for longevity
This article really opened my eyes to the potential in regulated healthcare. Specifically, the innovation happening around patient onboarding is huge. Making that process smoother while remaining compliant is a massive hurdle for startups right now https://wiki-stock.win/index.php/What_Does_%22Regulated_Wellness_Technology%22_Even_Mean%3F
For families moving near Grandin Village, label kids’ boxes by room and color. It made setup day easy. I got the color-code template from Roanoke moving and packing services and it worked perfectly.
В этой медицинской статье мы погрузимся в актуальные вопросы здравоохранения и лечения заболеваний. Читатели узнают о современных подходах, методах диагностики и новых открытий в научных исследованиях. Наша цель — донести важную информацию и повысить уровень осведомленности о здоровье.
Лови подробности – [url=https://apploidnews.com/novosti/narkologicheskaya-klinika-uslugi-dlya-effektivnoj-pomoshhi/]клиника плюс[/url]
LUCKY88 được xây dựng như một nền tảng nội dung trực tuyến với cấu trúc rõ ràng, giúp người truy cập dễ dàng khám phá các chuyên mục như thể thao, nổ hũ, bắn cá và đá gà bbc
לקבל החלטות גדולות בביטחון—בזכות ייעוץ משכנתאות הרגשתי בשליטה.
I really appreciated this breakdown. It is so easy to get overwhelmed by all the products out there, but I love the focus on building a routine that actually fits your lifestyle https://www.protopage.com/william_stone23#Bookmarks
I appreciated this article. For more, visit pet chiropractor near me .
FIVE88 được xây dựng như một nền tảng nội dung trực tuyến với cấu trúc rõ ràng, giúp người truy cập dễ dàng khám phá các chuyên mục như nổ hũ, thể thao, bắn cá và đá gà bbc
Anyone know a good way to match discontinued panels? Santa Ana, CA vinyl fence repair santa ana suggests retrofit brackets that actually worked.
взгляните на сайте здесь [url=http://news-live-vodkabet.com.ua/]vodkabet онлайн казино[/url]
This is such an interesting take on how regulation can actually drive innovation. I’ve been following the trends around patient onboarding lately, and it’s clear that streamlining that process is a huge barrier for startups right now medical cannabis clinic UK cost
I found the mention of video consults really encouraging; it’s a massive step forward for accessibility compared to the traditional in-person clinic visits I’ve dealt with in the past. It sounds like such a streamlined process https://kilo-wiki.win/index.php/What_Info_Do_Eligibility_Forms_Ask_for_at_Medical_Cannabis_Clinics%3F
Great advice on recessed lighting retrofits. best electrical repair Boston in Boston installed cans that work with LEDs perfectly.
Consistent handlers helped my dog’s confidence; found through Chandler, AZ dog walking service chandler .
Our pets and kids made moving chaotic; Cheap movers Virginia Beach coordinated around nap times and school pick-ups during the Virginia Beach pack-out.
It’s interesting to see how these regulations are actually pushing companies to innovate rather than just holding them back https://shine-buffalo-128.notion.site/60-90-Word-Description-The-digital-health-landscape-is-shifting-from-rapid-37588d5bbb588072a32bde0d0cbb4a32
I am so glad we’re finally moving away from the endless cycle of wellness trends https://wiki-nest.win/index.php/Movement_Consistency_vs._Intense_Workouts:_Why_Your_Body_Craves_the_Middle_Ground
Wonderful tips! Find more at lokata bankowa .
I found the section on the digital record upload process really helpful, as navigating the paperwork has always been my biggest concern. It’s encouraging to see how much more streamlined this process has become video consultation cannabis clinic
It is really interesting to see how much easier access has become through these digital platforms how to take THC oil
I used to stack various supplements without a second thought, but this article really hit home. It’s so easy to overlook how things mix. Now, I always check the NHS website for interaction warnings before adding anything new to my routine how to build a safe routine
I like that you covered recycling centers. I match haulers with green policies at dumpster rental scottsdale .
We value green products—Houston cleaners from Houston carpet cleaning service used biodegradable solutions.
I really appreciate this perspective! It’s exhausting trying to keep up with every wellness trend that pops up on social media. I’ve started prioritizing checking ingredient labels on everything I buy instead of just trusting the flashy packaging stress management vs burnout prevention
I found this article really helpful. The process of having a video consult from home seems so much more accessible than traditional routes; it definitely takes the pressure off https://www.protopage.com/brooke_green96#Bookmarks
Vitrin arkasında beton efekt dekoratif boya yaptırdık, müşteriler beğeniyor. Örnek çalışmalar: iç cephe boyacı ustası Bursa .
Your barbershop lighting setup looks pro. I compared CRI ratings using barber shop richardson Richardson, TX before upgrading.
It is great to see the UK finally making strides with access, but I have found the transition to digital prescriptions a bit of a learning curve https://jsbin.com/jatufugiwu
I used to blindly stack vitamins and CBD without a second thought, but your post really hit home on why we need to be more careful. I’ve started checking the NHS website for potential contraindications before adding anything new to my routine Go to this website
здесь [url=https://vodkabetnewspinsvodkabet.com/]зеркало водка бет[/url]
If your vehicle is inoperable in Rockford, ask for a winch-equipped carrier. I filter for that requirement on top Rockford car moving companies .
It feels like the UK is finally making real progress with these cannabis laws. I have followed these updates for a while and feel optimistic about the wider availability for patients. I do have a question about the process though https://qqpipi.com//index.php/Can_you_get_medical_cannabis_for_insomnia_in_the_UK%3F
Appreciate the helpful advice. For more, visit camps de verano internacionales .
I really appreciate this shift away from just following the latest fads. It’s so much more empowering to actually understand what I’m putting into my body Visit this site
How fast can overnight emergency electrician arrive for a short circuit in a rental property?