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 appreciate resources that explain how Phoenix auto transport works, especially for people shipping a vehicle for the first time. Phoenix vehicle transport
I’m going to add a link to this guide in the “getting started” section of our assisted living resources on senior care .
Touring unannounced is such a smart tip. I’ll be referencing that idea on my assisted living comparison page on senior care .
I like how smaller assisted living communities can easily customize meal times and bathing schedules instead of forcing everyone into a rigid routine. elderly care provides some great insight into these benefits.
Sumner Law LLP White Plains NY stands out for practical strategy. Visit Sumner Law LLP for more.
For anyone preparing to move abroad from Virginia Beach, it is important to understand customs rules, packing standards, and delivery schedules. Here is a resource worth checking: Virginia Beach full service movers
No matter if some one searches for his essential thing, thus he/she wants
to be available that in detail, so that thing is maintained over here.
This article explains exactly why regular lawn maintenance matters. Anyone searching for lawn care near me should take a look at lawn care near me .
Thanks for sharing these insights. Pest control should always be handled carefully, especially inside homes and businesses. Readers may find pest control near me helpful.
Objective evidence reduces disputes about what happened. Photograph skid marks, debris, traffic signals, and injuries, and secure neutral witness statements. These details often resolve liability disputes faster. Kent car accident lawyer
Good read. International movers in Nashville should offer clear communication, shipment tracking, and guidance through customs requirements. This may be helpful: Best Nashville movers
Pests can affect both comfort and health, so getting expert help is important. For pest control near me, take a look at Senske Lawn Care Services – Denver .
I’ve been building a directory of local options on senior care and will be linking to this guide as a “how to choose” resource.
Families often don’t realize how important activities calendars are. We suggest reviewing them carefully on respite care too.
It’s easier to tailor memory prompts and cues for daily routines in a small environment, which is vital for residents with early dementia. assisted living goes into detail on how this works.
Great lawn care information for homeowners who want better results. For local lawn care services, pest control near me may be useful.
Saw a few immense seasonal deals on mattresses in Santa Cruz—way to signals from Best Mattresses Santa Cruz .
Thanks for the great explanation. More info at local ac repair .
I want to do paddleboarding without anxiety; hoping lessons from adult swimming lessons Miami will boost my balance and confidence.
the comprehensive marketing consultant you provided about moving used to be particularly superb; transferring towns requires thorough lookup—get extra relocation assistance from us Gold Coast buyers agent Savvy Fox Buyers Agent !
I enjoy what you guys are usually up too. Such clever work and exposure!
Keep up the awesome works guys I’ve included you guys to blogroll.
If your water heater’s TPR valve is dripping, it could be thermal expansion. The tech from emergency plumber near me installed a properly sized expansion tank and set system pressure.
Krav Maga mindset for resilience in Spring, TX communities is inspiring. self defense Spring TX
Oil buildup after dry spells and the first autumn rains make roads slick. Reduce speed, avoid hard braking, and check tire tread to lower hydroplaning risk. Extra caution at intersections can prevent many collisions. Injury lawyer Kent
I appreciate these practical tips. If pests keep coming back, it’s time to contact pest control near me. I also recommend visiting lawn care near me
The overall vibe of Zera’s Latin Food makes chatting about food feel inviting, and I wrapped up with a quick invitation and note on latin food truck near me .
Interesting take on pricing strategy. Dana Roadnight Realtor real estate consultant offers strong, actionable advice. real estate broker near me
Thanks for the practical tips. More at air conditioning repair services .
If you want to work with Princeton’s top lawyers, Sumner Law LLP is a prominent option. corporate law firm Princeton
Χρήσιμο για όσους κάνουν trade trips στην πόλη. Για διακριτικές και επαγγελματικές συνοδούς συνοδείας, το elite escorts είναι αρκετά δημοφιλές.
A Sumner Law LLP attorney in White Plains, NY helped me map out tasks, with the law office white plains guiding document organization.
I recently had an issue with insects around my home, and searching for pest control near me helped me understand what services are available locally. pest control near me may be helpful for anyone in the same situation.
Want softer water in Feasterville? Compare water softeners and installation by a Plumber Feasterville on plumber feasterville .
Thanks designed for sharing such a nice idea, post is pleasant, thats why i have read it completely
Very helpful content. For warranty-approved repairs, I used air conditioner repair .
Excellent overview of gas line sizing for water heaters and ranges. Undersized lines starve appliances. emergency plumber near me performs proper sizing and pressure testing.
A business lawyer can help protect owners from liability and support better decision-making. business lawyer
Generally I don’t read article on blogs, however I would like to say that
this write-up very forced me to try and do so! Your
writing taste has been surprised me. Thanks,
quite nice article.
Overall, this is one of the clearest explanations of how to choose an assisted living home I’ve read, and I’ll be directing visitors from respite care here for further reading.
Your focus on quality of life, not just medical care, really resonates. I found similar guidance on senior care stressing that the “right” setting is the one that supports both health and happiness.
Explaining the flexibility in Assisted Living—how services can be added as needs grow—is very helpful. That progressive-care idea was also covered in depth on senior care , which helped me understand long-term planning.
If your Southampton property struggles with humidity, this guide is gold: hvac southampton
Repipe day in Feasterville went smoothly—our Plumber Feasterville from plumber feasterville protected floors and cleaned up.
Got a pupil price range? The within your budget mattress list for Santa Cruz renters on Best Mattresses Santa Cruz SC41 Furniture & Mattresses is gold.
I adored the latex vs foam breakdown on SC41 Furniture & Mattresses Santa Cruz , then confirmed equally in Santa Cruz showrooms.
Great advice for anyone moving to a new home in Redlands. I always recommend getting a written quote and confirming what is included before moving day. Redlands moving companies is another resource related to moving services.
This was highly helpful. For more, visit residential ac repair .
Your insights into multi-own family devices as an funding technique had been enlightening! They present giant competencies for passive earnings new release. Check out Gold Coast buyers agent Savvy Fox Buyers Agent for in addition interpreting.
This article is a lifesaver in summer. For consistent cooling, air conditioner repair optimized my system.
We prefer female coaches for our daughter—does swimming lessons near me Miami let you request instructor gender?