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 love how this article breaks down DIY mini splits, especially mentioning the SEER 20 rating and the $1,000-$3,500 price range. It makes the idea of installing one myself seem much less intimidating how to get started with google assistant mini split
For facet sleepers in Santa Cruz, I stumbled on a widespread power-relief guide on Best Mattresses Santa Cruz SC41 Furniture & Mattresses that extremely helped my possibility.
This is quite enlightening. Check out affordable residential ac repair for more.
I love the idea of swapping black for burgundy in summer outfits—adds such a rich warmth without feeling too heavy. I’ve also been experimenting with mesh layering lately; it feels breathable but still gives that edgy vibe enterprise platform sandals goth
I really appreciated the point about low overhead in home services franchises—it seems like a smart way to start without heavy upfront costs start a carpet cleaning business Queensland
I love that you highlighted strap adjustability—when I commute daily, being able to lengthen or shorten my crossbody bag makes such a difference for comfort https://www.hometalk.com/member/249527461/harriet1547848
I just checked my homeowners policy and realized my wind and hail deductible is actually 2%, which is way higher than I thought. Also didn’t know about the difference between ACV and replacement cost until reading this https://jsbin.com/jubelafiyu
I really appreciated the tip about stocking up on vests and sleepsuits. Having plenty of those basics made dressing my newborn so much easier, especially during quick diaper changes Click to find out more
Reveal unique promotions at Kaizenaire.com, covering Singapore’ѕ shopping platforms.
Singapore’ѕ global popularity as a shopping destination іs driven by Singaporeans’ undeviating love
fօr promotions ɑnd savings.
Singaporeans tɑke pleasure іn mapping out city landscapes
in note pads, ɑnd bear in mind to stay updated on Singapore’ѕ
most recent promotions ɑnd shopping deals.
FairPrice, а prominent supermarket chain, stocks groceries ɑnd
home fundamentals аt affordable costs, ⅼiked by Singaporeans for their everyday worth
and community support.
Millennium Hotels ߋffers high-end accommodations ɑnd hospitality solutions
οne, treasured by Singaporeans fоr tһeir comfy гemains and prime
areas mah.
Scent Bak Kwa grills tender jerky slices, preferred fοr aromatic, melt-іn-mouth joyful treats.
Wah, so good leh, promotions ᧐n Kaizenaire.com waiting one.
my web-site – singapore promotions
Combination sleepers, payment the responsiveness rankings on SC41 Furniture & Mattresses Santa Cruz ; suits what I attempted in Santa Cruz.
Great insights on the contenders and dark horses! I’m really curious to see how Spain manages the rotation with the grueling travel and heat challenges, especially since players like Odegaard will need to stay sharp throughout https://www.mapleprimes.com/users/christopherdavis24
This was a constructive examine. Proper drainage and gutter upkeep are so incredible for preserving roofing systems in Southeast Texas. roofing company houston tx
Great overview of the upcoming pharma executive conferences! The mention of 20,000+ attendees at BIO really stood out—it’s impressive how big these gatherings are becoming Visit this website
The discussion on funding residences became enlightening! I’m eager to dive into that industry myself. Check out Gold Coast buyers agent for extra tricks.
I really appreciate the focus on breathable fabric in newborn wardrobes. It makes those 3 a.m. changes so much easier and more comfortable for baby and me easy nappy change outfits
I absolutely relate to this! I joined a small group trip last year, and I was so nervous about that awkward first night. But sharing meals together really helped break the ice, and some of us still keep in touch months later travel to meet people 2026
Just checked my policy, and I had no idea about the 2% deductible on hail damage—definitely more than I expected. Also, the difference between ACV and replacement cost was a real eye-opener hail damage roof inspection services
שירות אמין עם תודעת לקוח גבוהה במיוחד. עוד מידע: מציאת יועץ פיננסי מומלץ
I absolutely agree that breathable fabrics are a game changer for newborn wardrobes. My little one was so much more comfortable in soft cotton onesies during those sleepless 3 a.m. changes newborn skin irritation clothing for business
I really appreciated the tip about installing pre-charged lines with these mini splits. It makes the whole process less intimidating, especially for someone like me who’s just getting into HVAC DIY projects View website
I really relate to this! I joined a small group trip last year, and honestly, the first night felt a bit awkward. But sharing meals together made it so much easier to connect. We’re still in touch and even planning a reunion wellbeing and friendships
I love the idea of swapping black for burgundy on warmer days—such a fresh twist that still feels chic. Also, mesh layering seems like a game changer for staying cool without sacrificing style https://dylan-nelson90.raindrop.page/bookmarks-72522205
I really appreciated the point about the 12-18 month rebook cycle—makes so much sense for service franchises to build repeat business that way Go to this site
I love that the article highlights strap adjustability because as a daily commuter, having a bag that fits comfortably whether I’m biking or walking is a game changer https://www.protopage.com/faith_torres31#Bookmarks
Great insights on the travel and heat challenges teams will face in the 2026 World Cup! I’m especially curious how Morocco will handle these factors as potential dark horses Visit this link
Great overview of upcoming pharma conferences! The BIO event expecting 20,000+ attendees in 2026 is impressive. For companies investing heavily, it’d be useful to hear strategies on maximizing ROI through targeted partnering meetings https://atavi.com/share/xx52fkz5p2pi
I totally agree with this! I joined a small group trip last year and was nervous about meeting new people, especially during that awkward first night Helpful resources
Just checked my policy and realized I have a 2% wind and hail deductible—didn’t know that would come out of pocket first. Also learned my claim would be based on actual cash value, not replacement cost, meaning I could be stuck paying for depreciation https://samantha-palmer00.raindrop.page/bookmarks-72522538
sportwetten in österreich
Feel free to surf to my web site; basketball over under wetten system
I love how you highlighted the importance of breathable fabric for newborns. Those 3 a.m. changes are so much easier when clothes don’t irritate their skin! I definitely overbought newborn sizes before realizing babies grow out of them in a flash soft baby onesies for professionals
Regular lawn service can keep weeds under control and improve curb appeal throughout the year. Check pest control near me for local lawn care options.
This was very beneficial. For more, visit power washing Manorville .
Thanks for the insightful write-up. More like this at cincinnati air conditioning repair .
I absolutely relate to this! On my last small group trip, the first night felt a bit awkward as everyone was getting comfortable, but sharing meals really helped break the ice. By the end, I had made friends I still keep in touch with https://www.protopage.com/tyler-jones04#Bookmarks
Thanks for the useful post. More like this at pressure washing services .
Got a pupil price range? The competitively priced bed list for Santa Cruz renters on Best Mattresses Santa Cruz SC41 Furniture & Mattresses is gold.
For warm Santa Cruz afternoons, breathable covers from brands on Best Mattresses Santa Cruz are clutch.
A business lawyer can help ensure that company policies and agreements comply with applicable laws. Jeremy Eveland
Thanks for highlighting the position of social media in true property marketing—it truly is such an productive device at this time to connect to competencies dealers or renters—be trained greater thoughts from our web site, visit Gold Coast buyers agent !
Valley installation can make or break a roof. I prefer closed-cut valleys for aesthetics. Tutorials on ebenezer roofing roof repair manassas va .
Aw, this was an incredibly good post. Taking the time and actual effort to generate a really good article… but what can I say… I hesitate a lot and don’t manage to get anything done.
This was very beneficial. For more, visit commercial ac service .
excellent issues altogether, you simply received a new reader.
What may you suggest about your submit that you just made some days in the
past? Any positive?
neues casino slots hamburg (Haley) maximaler bonus
Great issues the following. Mold, moisture, and hidden leaks can develop into serious troubles when roofing problems go unchecked. Strawhat Roofing roofing installation services
I really appreciated the tip about checking the back of the neck for irritation when choosing newborn clothes. It’s something I hadn’t considered before and will definitely help keep my baby comfortable. Thanks for the practical advice! https://wiki-velo.win/index.php/How_Do_I_Dress_My_Newborn_for_a_Day_That%27s_Cold_Morning_and_Warm_Afternoon%3F
I really appreciated the tip about checking the back of the neck for irritation. It’s something I hadn’t thought about, but seems so important for keeping baby comfortable. Stocking up on sleepsuits also sounds like a lifesaver for busy nights https://johnathanytzx289.image-perth.org/do-babies-really-go-through-clothes-at-an-alarming-rate
ניתוח סיכונים והשקעות מותאמות אישית – קיבלתי ב- שיקום כלכלי ייעוץ .
другие https://trip75at.us
Glad you highlighted acceptable enables. Our roofing contractor Manassas Virginia ( gutter services ) taken care of Prince William enables and HOA approvals seamlessly.