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
}
After a bad experience with another Sacramento Appliance Repair company, I was skeptical about calling Urgent Appliance Repair Sacramento appliance repair companies near me
Looking for reliable Naperville car transportation services? I had a smooth door-to-door experience last month—check out Naperville car shipping for quick quotes and scheduling.
Considering LCL from Oyster Bay to New Zealand? Get a consolidation schedule—mine was transparent thanks to Cheap movers Oyster Bay .
If you’re relocating from Seattle to Tacoma on a budget, cross-check rates on Safe WA Mover’s first.
We fastened choppy cooling after examining balancing suggestions from Astar Air Conditioning, Plumbing & Electric at AC Repair Dallas .
¿Cuál es el mejor tipo de cerradura para una puerta principal? Me encantaría saber tu opinión. cerrajero barcelona
Appreciate the insightful article. Find more at mejor pensión en Arzúa .
It’s the best time to make some plans for the future and it is time to be happy.
I’ve read this post and if I could I want to suggest you some interesting things or suggestions.
Maybe you can write next articles referring to this article.
I wish to read even more things about it!
The DIY toy rules are so creative. Our cats cross wild for the new treats you instructed. pet monkeys for sale
I totally relate to this. Since I started working remotely, the line between my office and bedroom has just vanished. I find myself mindlessly scrolling through videos late at night-driven by that endless autoplay feature how to stop scrolling in bed
I never realized how connected the spine is to overall wellness until I tried chiropractic care. Car accident chiropractor
This was highly informative. Check out polígono industrial Campollano for more.
I totally get this. Between the endless scroll and that autoplay feature it is so hard to disconnect after working from home. My brain just refuses to switch off. One thing that actually helped was moving my phone charger out of the bedroom https://blogfreely.net/gertonmhvf/why-does-my-sleep-schedule-get-worse-when-im-stressed-about-money
It is wild how much the game has shifted toward off-field maintenance lately. Players seem more stressed about their sleep metrics than the actual playbook sometimes https://echo-wiki.win/index.php/Individualized_Health_Planning:_Moving_Beyond_the_Buzzwords_in_Sports_Performance
I’ve been using sleep tracking features on my watch for a few months now, and it’s honestly been a game changer for my routine. It’s fascinating to see the data broken down every morning https://noon-wiki.win/index.php/What_Does_Product_Transparency_Look_Like_for_Wellness_Tech%3F
Way cool! Some very valid points! I appreciate you penning this post and also the rest of the site is very good.
I’ve definitely felt that frustration when a slot hits a 200 spins cold streak despite a high RTP. It makes the volatility feel like a total mystery until you see the math behind it bonus round math
В данной статье рассматриваются проблемы общественного здоровья и социальные факторы, влияющие на него. Мы акцентируем внимание на значении профилактики и осведомленности в защите здоровья на уровне общества. Читатели смогут узнать о новых инициативах и программах, направленных на улучшение здоровья населения.
Получить исчерпывающие сведения – [url=https://lulustyle.ru/kapelnitsy-ot-zapoya-kak-oni-pomogayut-i-gde-mozhno-poluchit/]лечение алкоголизма в Курске[/url]
I’m not sure exactly why but this weblog is loading incredibly
slow for me. Is anyone else having this issue or
is it a issue on my end? I’ll check back later on and see if the problem still exists.
This article really hits home. Ever since I started working remotely, the lines between my office and bedroom feel so blurred. I often get trapped in the endless loop of social media scrolling and video autoplay late at night why modern life is exhausting
I’ve been using a new ring to monitor my HRV lately, and it’s honestly been eye-opening to see how my stress levels fluctuate throughout the day. It really helps me decide when to dial back on workouts https://jsbin.com/?html,output
If your campaigns want brand new ingenious swift, Fast Hippo Media is worth a look: Digital Marketing McKinney TX .
It is wild how much pressure these guys are under now to track every single metric https://juliussinterestinginsight.image-perth.org/the-recovery-coordinator-why-modern-sports-performance-is-less-about-ice-baths-and-more-about-logistics
Tavan sararmalarını kapatmak için leke tutucu astar şart. Uygulama sırası ve ürün önerileri için Bursa iç cephe boya badana içeriği oldukça açıklayıcı.
I never realized how much hidden volatility affects these games until I read this. That 200 spins cold streak I hit last week finally makes sense now. It definitely changes how I approach my bankroll management https://simonvsaz605.almoheet-travel.com/what-s-a-good-checklist-for-reading-a-slot-s-temperament
I needed a last-minute spot in Brisbane and got a seat via white card Brisbane training .
I really enjoyed this breakdown of the latest wearable tech. I’ve been using sleep tracking features for a few months now, and it’s been eye-opening to see how my evening habits actually affect my recovery how to choose sleep tracking app
It is fascinating to see how digital wellness is evolving here in the UK. The shift toward video consultations for medical cannabis access really streamlines the process for many patients digital patient platforms UK
It is wild how much the game has shifted toward high-tech recovery. The article mentions the travel-heavy schedule, which has to be brutal on the mind https://www.instapaper.com/read/2020682926
This blog lines up with what I discovered in class; scheduled using Cannon Hill white card courses for white card Gold Coast qualification.
I’ve definitely felt that frustration when a slot hits a 200 spins cold streak despite a high RTP. It makes the volatility feel like a total mystery until you see the math behind it micro bets slots
I’ve been researching this for a while and didn’t realize how important it is to have your full medical records ready before the first consultation. That definitely makes the process feel more legitimate https://ace-wiki.win/index.php/Do_You_Need_a_Specialist_to_Prescribe_Medical_Cannabis_in_the_UK%3F_A_Patient-First_Guide
I liked that they issue interim proof; Gold Coast white card training helped me begin job while my white card Gold Coast was processed.
I love how chiropractic visits include both adjustments and lifestyle coaching. Chiropractor Tacoma
This is such a fascinating look at how digital health is changing access to treatment here in the UK. I found the shift toward video consultations especially interesting for those of us living far from specialist clinics https://rentry.co/8x2ud7ok
It’s really helpful to see this broken down. My main takeaway is how vital it is to have your full medical records ready before that first consultation since it really speeds things up https://jsbin.com/femazijuyu
This is such a timely piece. I have been experimenting with personalised breathwork routines lately, and it is honestly changing how I handle mid-week stress. It feels much more effective than the one-size-fits-all approach we saw a few years ago https://wiki-cafe.win/index.php/Is_Holistic_Wellness_Legit_or_Just_Another_Marketing_Trend%3F
The info on demand letters was solid; accident attorney can draft a compelling one.
A friend in Sacramento warned me about overpaying for Appliance Repair work. Glad I called Urgent Appliance Repair Sacramento — their pricing was transparent and competitive for our home near Northern California Regional Public Safety small appliance repair near me
Yesterday, while I was at work, my sister stole my apple ipad and tested to see if it can survive a forty foot drop, just so she can be a youtube sensation. My iPad is now destroyed and she has 83 views. I know this is completely off topic but I had to share it with someone!
The safety checklist is spot-on for families with kids and pets. For more lighting hacks, visit Outdoor Holiday Lighting Vancouver
It is fascinating to see how digital wellness is evolving, especially with medical cannabis clinics here in the UK. I found the shift toward secure record uploads really interesting from a patient privacy perspective mindfulness apps UK
We used their seasonal promo for a bathroom refresh—facts at Prestige Home Remodeling .
Thanks for this clear breakdown. I didn’t realize how important it is to have your full medical records ready before the first consultation. That definitely saves a lot of stress during the initial process patient monitoring medical cannabis
If you’re new to Clifton, ask movers for neighborhood tips too. I met a great local crew through Cheap movers Clifton who knew all the building policies.
I really appreciate this perspective on how wellness is shifting here in the UK. Dealing with burnout has been such a challenge lately, and I love that we are moving away from one-size-fits-all solutions recovery-focused fitness for seniors
Data cleanliness first; we put into effect UTM governance—components at best seo company in Farmers Branch .
I have actually been looking for the best Chiropractor near me in St Augustine and maintained seeing outstanding reviews regarding Pain Relief Centre. After my very first see, I comprehended why– expert treatment, personalized therapy, and real results chiropractor st augustine
I’ve been trying to find the very best Gutters replacement company near me and kept discovering multiple outstanding evaluations about A+ Gutters for Ponte Vedra Beach gutters
It is really interesting to see how the UK wellness scene is evolving in 2026. I have been using guided breathwork lately to manage my daily stress levels, and it makes such a difference More help