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’ve definitely felt that range anxiety when the estimate drops faster than expected. It’s always a tough choice on the motorway, especially when you’re pushing for time https://solo.to/dylan-holt09
I appreciate that many small assisted living homes avoid long institutional hallways and confusing layouts. It’s easier for seniors to navigate to the bathroom or dining area. assisted living points this out as a key benefit.
I really appreciated this perspective! I’ve been trying to be more intentional lately. Usually, while I’m standing in line waiting for my morning coffee, I automatically reach for my phone to listen to a podcast https://www.instapaper.com/read/2020127484
Thanks for the simple checks to do at home. When they didn’t fix it, AC maintenance in Lewisville in Lewisville handled the repair.
I really appreciated your take on the friction in conversion. As someone running a smaller e-commerce shop, I think the focus on a frictionless signup process is something we often overlook in favor of collecting too much data early on https://www.protopage.com/scottpowell94#Bookmarks
Эта публикация исследует взаимосвязь зависимости и психологии. Мы обсудим, как психологические аспекты влияют на появление зависимостей и процесс выздоровления. Читатели смогут понять важность профессиональной поддержки и применения научных подходов в терапии.
Углубить понимание вопроса – [url=https://crimeabest.com/vyvod-iz-zapoya-kak-preodolet-tyazheloe-sostoyanie/]clinica plus[/url]
It is interesting to see these apps shifting toward a gaming feel. I agree that the interface makes them much more accessible, but it can definitely blur the lines for some users instant win games
Great tips. If you’re in Canton, MA and need AC repair, AC maintenance in Canton MA is a good option.
Chose OBG for the 10-year warranty as much as the price. Knowing the investment is covered for a decade gives real peace of mind when spending several thousand pounds on a new garage. Very satisfied. concrete garages glasgow
Πολύ ενδιαφέρον άρθρο για τις Μεταφράσεις! Για όποιον θέλει επαγγελματική βοήθεια, ρίξτε μια ματιά και στο οικονομικές μεταφράσεις για εξειδικευμένες γλωσσικές υπηρεσίες.
Asking how they handle end-of-life care in assisted living is difficult but necessary. We discuss having those conversations on elderly care .
Great suggestion to observe resident-staff interactions during a tour. I’ll direct readers to think about that on senior care .
It’s helpful to know that Independent Living is often more about convenience—meals, housekeeping, and social activities—rather than nursing care. I first learned that distinction through reading guides on assisted living .
Honestly, there is something so comforting about returning to those retro titles. It hits that nostalgia itch perfectly whenever I need a break from these overly complex modern games. It is wild how well-designed those old classics are even decades later Learn more here
It is fascinating how architects are now treating spaces like interactive stages. I particularly loved your point about circulation as story pacing. It makes so much sense that the path we walk through a building dictates our mood casino layout design
It’s fascinating to see how the industry has shifted since IGRA 1988 first set the legal framework for tribal gaming https://atavi.com/share/xw712hz1u8k2s
This was highly educational. More at garage door repair services .
The 10-year warranty was important to me when choosing a garden room builder. Knowing it is insurance-backed rather than just a promise from the company gave me real peace of mind. OBG delivered. Garden Room Glasgow
I honestly love that post-game buzz. The first thing I do every morning is check the highlights to see if I missed any wild plays. Our group chat is always absolute chaos dissecting the London Lions game from the night before https://lisa-cox07.raindrop.page/bookmarks-72026174
Can’t wait to dive into my pool this weekend! Opening day is almost here! pool opening
This piece really hit home for me. As a parent of two toddlers, the “productivity guilt” mentioned is a constant struggle. I often feel like if I’m not actively cleaning or meal prepping during nap time, I’m somehow wasting precious time https://www.protopage.com/colin_kim96#Bookmarks
I totally get this. The “guess-o-meter” can be so stressful on long trips, especially when the temperature drops in the winter and the range just plummets how to maximize ev efficiency
I never thought about it this way, but that makes a lot of sense. The way games use chance often feels stressful, yet the immediate feedback loop is what actually keeps me coming back contained unpredictability
I definitely needed this perspective today. I find myself mindlessly scrolling through short videos every time I’m waiting for my morning coffee at the local shop, and it really eats into my headspace outdoor and digital balance
Seat belt defense myths abound; get the facts at affordable car crash attorney .
Drunk driving accidents often allow punitive damages—details at car accident attorney for injury claims .
Эта публикация содержит ценные советы и рекомендации по избавлению от зависимости. Мы обсуждаем различные стратегии, которые могут помочь в процессе выздоровления и важность обращения за помощью. Читатели смогут использовать полученные знания для улучшения своего состояния.
Узнать из первых рук – [url=https://vsairnav.ru/nachat-s-chistogo-lista-kak-rasplanirovat-god-chtoby-provesti-ego-plodotvorno/]клиника плюс[/url]
I definitely love how jewelry can change a whole clothing! It’s amazing how an easy piece can add so much beauty and character. Have you ever thought of personalizing your own jewelry? It can produce a really unique declaration piece sell gold
If a defective part caused your crash, product liability may apply; explore it at experienced lawyer .
The reminder to check staff-to-resident ratios is crucial. I plan to expand on this topic with more details linked via senior care .
Soft tissue injuries are often minimized by insurers; learn to counter that at lawyer .
Evidence like dashcam footage can be crucial—see tips on preserving it at attorney .
As someone helping a grandparent transition from home care, the distinctions between Assisted Living and Nursing Homes are critical. I found the comparison here similar to what I saw explained on respite care when exploring senior care levels.
Our landlord hired Precision Emergency Plumber Los Angeles for Emergency Plumber work at our Los Angeles rental near Los Angeles County Fire Dept. Station 54 24 7 plumber near me
The idea of trial stays or respite care as a test run is brilliant. We mention this as an option on elderly care as well.
This was beautifully organized. Discover more at tienda a granel urbana .
Love that you encourage families not to rush the process. We have a step-by-step timeline on dementia care that supports that mindset.
Great overview! Plano residents: booking links are on preventive dentistry .
I found this very helpful. For additional info, visit Pressure washing company .
Incredible quest there. What occurred after? Good luck!
Kurallara saygılı, zaman yönetimi iyi olan profiller bulmak zor; bu noktada özel eskort Diyarbakır düzenli güncellemeleriyle öne çıkıyor.
Write more, thats all I have to say. Literally, it seems as though you relied on the video to
make your point. You obviously know what youre talking about, why throw away your intelligence
on just posting videos to your blog when you could be giving us something enlightening to read?
For facial sculpting without harsh techniques, Lymphatic Drainage Massage is fantastic. Tutorial at lymphatic drainage massage .
Visited three garage companies before choosing OBG. The combination of price-match guarantee, no upfront payment, and 10-year warranty made them the obvious choice. The finished garage confirms it was the right decision. concrete garages glasgow
В этой статье рассматриваются различные аспекты избавления от зависимости, включая физические и психологические методы. Мы обсудим поддержку, мотивацию и стратегии, которые помогут в процессе выздоровления. Читатели узнают, как преодолеть трудности и двигаться к новой жизни без зависимости.
Изучить вопрос глубже – [url=https://odincrk.ru/preodolenie-zavisimosti-bezopasnyj-vyhod-iz-zapoya/]капельницы от похмелья в Ижевске[/url]
Your advice on taking weekly measurements was key. I used a tracker from body contouring and stayed encouraged.
The free site survey was genuinely useful. The estimator suggested a positioning I had not considered that gave us much better natural light. The finished Kai is stunning and my wife uses it as her art studio. Garden Room Glasgow
Great rates and honest technicians — HVAC repair in Hutto is my go-to for AC repair in Hutto.
Scheduling versatility and qualified staff are so important when choosing a daycare. Value the insights here; eagerly anticipating exploring what dog day care has to provide.
Wonderful, what a webpage it is! This weblog provides helpful data to us,
keep it up.