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 comparing three bids, I chose a mid-priced enclosed carrier via Lincoln enclosed car shipping for peace of mind.
This was helpful, especially the reminder to start packing earlier than expected. Anyone moving around Indianapolis should definitely compare services before choosing a moving company. Indianapolis movers
Nice post. Whether shipping a sedan, SUV, or classic car, choosing a reliable transport provider in Santa Ana makes a big difference. Related info: door-to-door car transportation Santa Ana
Great insights! Find more at https://massapequapressurewashing.com/services/pressure-washing/#:~:text=Professional-,Pressure%20Washing%20Services%20in%20Massapequa%2C%20NY,-Business%20owners%20and .
I’ve been researching options for a reliable BBQ islands contractor in Orange County, and landscaping companies orange county ca keeps coming up in local recommendations. Has anyone here worked with them on a custom outdoor kitchen?
If your car sits low, ask for soft tie-downs. I requested it on Chesapeake car shipping services and my Chesapeake carrier complied.
Wonderful tips! Discover more at fachadas y escaparates de aluminio .
Have you considered seeing a ##Puyallup Chiropractor## for your posture? It’s been a game-changer for me! Chiropractor Puyallup
This was very enlightening. For more, visit Teléfono taxi Arzúa .
The clarity you provide around expectations for rehabilitation, long-term nursing care, and palliative support is helpful. I found matching information on senior care when we were considering post-hospital options for my dad.
Pets and personal belongings can make a huge difference. We encourage families to ask about that on assisted living .
It’s wise to check cancellation policies and what happens if care needs change suddenly. We explain this in more detail on respite care .
Hi to every single one, it’s in fact a fastidious for me to visit this site, it contains important
Information.
В этой заметке мы представляем шаги, которые помогут в процессе преодоления зависимостей. Рассматриваются стратегии поддержки и чек-листы для тех, кто хочет сделать первый шаг к выздоровлению. Наша цель — вдохновить читателей на положительные изменения и поддержать их в трудных моментах.
Кликни, не пожалеешь – [url=https://psihter.ru/prochee/vyhod-iz-zamknutogo-kruga-pochemu-domashnie-metody-ustupayut-professionalnoy-narkologicheskoy-pomoschi/]анонимное лечение алкоголизма в стационаре[/url]
Great insights on keeping cool during LA’s heat waves! In a city where summer temps can spike and older buildings struggle with airflow, having a reliable HVAC plan is everything browse around this site
Person-centered care is easier to achieve when the community is small. Caregivers really get to know each resident’s history and triggers. I discovered that many small homes operate this way through sites like dementia care .
With a Kent personal injury lawyer, you avoid common claim mistakes that reduce settlement value. Personal injury lawyer in Kent
Thanks for the valuable insights. More at albergue en Palas de Rei .
Surrogacy is a huge emotional and financial commitment, so choosing the right Riverside agency is critical. I’ve been reading guides on riverside surrogacy agencies that explain what red flags to look out for and how to verify an agency’s credentials.
Seeing real client experiences in Orange County on regenerative medicine orange county gave me the confidence to finally try Botox for my forehead wrinkles.
cash best sports betting tips; Christiane, app
A well maintained facility usually gives me more confidence about long term storage storage units
Your checklist for evaluating phone system vendors is very practical. Anyone in California reviewing options might want to include providers like Technology Relocation Experts California in their shortlist to compare service levels and features.
This article really highlights how important quality materials are for outdoor kitchens. In Orange County, I’ve noticed companies like landscaping companies orange county ca using high‑end stone and stainless components that can handle the coastal climate.
В данной публикации мы поговорим о процессе восстановления от зависимости, о том, как вернуть себе нормальную жизнь. Мы обсудим преодоление трудностей, значимость поддержки и наличие программ реабилитации. Читатели смогут узнать о ключевых шагах к успешному восстановлению.
Изучить вопрос глубже – [url=https://pediatrinfo.ru/the_articles/kapelnitsa-ot-alkogolya-kak-detoksikatsiya-pomogaet-organizmu-spravitsya-s-intoksikatsiey.html]прокапаться от алкоголя в воронеже[/url]
If you’re in Timperley and desire a nearby dentist, examine Dental Aesthetica Altrincham Dentist Altrincham for nearby solutions.
Looking forward to exploring the Newport Beach coastline with a professional captain from newport beach boat rentals with captain at the helm.
I think many people underestimate the importance of unit ventilation storage units
Great tips! For more, visit Servicio de taxi local Arzúa .
This was very enlightening. More at abogado 24 horas Santiago .
Thanks for the great tips. Discover more at albergue privado Palas de Rei .
Awesome post.
https://m-g.wine/
Thanks for highlighting the importance of personal choice in daily routines. We focus on person-centered care models on elderly care .
Seniors with mobility challenges often do better in a compact, familiar setting. In a smaller home, it’s easier to safely assist with transfers, bathing, and grooming. respite care appears to understand this need.
The way you highlighted social engagement in Independent and Assisted Living is so important. Loneliness is a big issue for seniors. I saw similar advice on respite care , which stresses the value of community in senior living.
In small homes, ADL support can be discretely woven into the day instead of feeling like a medical procedure. That subtlety, highlighted by elderly care , helps preserve dignity.
This was highly educational. For more, visit persianas y mallorquinas aluminio .
Just had an adjustment from my favorite ##Puyallup Chiropractor## and I feel like a new person! Puyallup car accident chiropractor
Your focus on routine and structure as cornerstones of memory care is right on target. That consistency can greatly reduce anxiety. We share sample daily routines at dementia care .
I like that I can filter for “with captain” on newport beach boat rentals with captain for Newport Beach boat rentals.
Appreciate the thorough analysis. For more, visit Super Clean Machine | Power Washing & Roof Washing .
Hello folks, I recently decided to explore plastic window frames in Amsterdam and I must say it has been quite the journey — I contacted a kunststof kozijnen amsterdam specialist and they were really professional when it came to installing the frames, and after asking for a https://wiki.seti-hub.org/w/index.php?title=User:RorySinnett kozijnen amsterdam offerte I was pleasantly surprised by how affordable the total cost was compared to what I anticipated — the local business I ended up using was clearly the best supplier I discovered, and their skilled technician did a spotless job with the frame replacement, so if you are hunting for budget-friendly frames I highly recommend doing your research first!
This was highly helpful. For more, visit Power Washing Pros of Massapequa | House & Roof Washing .
Before accepting any settlement, talking to a Kent personal injury attorney can prevent major financial loss. Kent car accident attorney
For other couples considering surrogacy in Riverside, I recommend learning as much as you can before signing with any agency. I found that riverside surrogacy process helped me understand the overall process, from screening to matching and final legal steps.
יועץ פיננסי מומלץ שמלווה לאורך זמן – זה מה שמצאתי אצל ייעוץ משכנתאות למתחילים .
Thanks for highlighting the importance of call quality and uptime guarantees. In a competitive market like California, that really matters. I’ve noticed providers such as Cabling Services Provider California emphasizing reliability and support as key selling points.
Code Promo 1xbet Burundi offre un bonus inscription 1xBet de 100% sur votre premier depot, disponible en Afrique ou dans d’autres regions, jusqu’a 130€ selon votre devise. 1xBet, un bookmaker repute dans le domaine des paris sportifs, est etabli depuis plus de dix ans.
I appreciated the sooner than-and-after galleries for Altrincham smile makeovers on Dental Aesthetica Altrincham Dentist Altrincham .