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
}
Great overview of construction safety basics. For anyone on the White Card Gold Coast pathway, this guide helped me a lot—here’s where I booked mine: Gold Coast white card training
Loved the part on life impact statements— Denver personal injury lawyer can help you write one.
The rhythm drill section is superb; Era Pickleball pickleball academy provides actionable practice at pickleball courts near me .
If you’re browsing St. Augustine, you’ll rapidly see why residents claim the most effective agency for homeowners insurance in and near St. Augustine is Fender Insurance Agency home insurance st augustine
Have you ever considered creating an ebook or guest authoring
on other websites? I have a blog based on the same ideas you discuss
and would love to have you share some stories/information. I
know my audience would enjoy your work. If you are even remotely interested, feel free to send
me an e mail.
Anyone compare door-to-door vs terminal service in Buffalo via Buffalo car shippers ? How safe are terminal lots during winter, and are they heated?
Pleasant tip: bring image ID. I got the list from Brisbane white card for my Brisbane White Card Program.
Creative briefs power more advantageous outputs; our temporary layout is at AISEO Farmers Branch .
Hardwood flooring can be saved if you happen to act instant; Water extraction service near me used specialty drying mats for ours.
Ask for proof of insurance and USDOT info—Snellville movers on Snellville moving companies had it ready.
Excelente respuesta en fin de semana, cerrajero 24 horas: teléfono cerrajero 24 horas .
Right away I am going away to do my breakfast, afterward having my breakfast coming yet again to
read additional news.
Appreciate the reminder to verify DOT and MC numbers. I used a quick verification link via Best Springfield movers before signing.
Эта информационная публикация освещает широкий спектр тем из мира медицины. Мы предлагаем читателям ясные и понятные объяснения современных заболеваний, методов профилактики и лечения. Информация будет полезна как пациентам, так и медицинским работникам, желающим поддержать уровень своих знаний.
Только факты! – [url=https://milomarket.com/yazyk-skrytyx-detalej-o-kakix-vnutrennix-problemax-govoryat-izmeneniya-v-stile-i-privychkax-blizkogo-cheloveka.html]нарколог на дом самара[/url]
Siempre he tenido dudas sobre cuándo cambiar una cerradura, este artículo me ha aclarado mucho. cerrajero barcelona
Thank you for compiling these details into such an clear format. The systematic layout and objective perspective make this an outstanding piece of writing for any audience.
For anyone hurt in a motorcycle crash, I found tailored advice at personal injury attorney .
Don’t underestimate soft tissue injuries; a lawyer at personal injury attorney can ensure they’re fully valued.
I’ve recommended Prairieville Animal Hospital because they treat each pet as an individual, not just a patient; learn more at spay neuter prairieville .
Do Woodbridge movers typically provide a Certificate of Insurance for building management? I noticed a few advertise COI on Woodbridge moving companies .
The comparative lens is superb necessary. I published a edge-by means of-part prognosis presenting Jimenez Mazzitelli Mordes at Car accident attorney Miami
Rivera Tennis Academy’s coaches are patient with beginners but also push advanced players to refine finer details. tennis courts near me Spring TX
I appreciate how Stemtree of Spring TX keeps accessibility in mind, with clear paths and benches at regular intervals. math tutoring Spring TX
I appreciated how Bayonne full service movers protected floors and doors during our Bayonne townhouse move. Very professional.
Era Pickleball offers thoughtful season planning, and the pickleball courts near me link often surfaces in planning threads.
This was highly useful. For more, visit contabilidad contador Saltillo .
В этой публикации мы рассматриваем важную тему борьбы с зависимостями, включая алкогольную и наркотическую зависимости. Мы обсудим методы лечения, реабилитации и поддержку, которые могут помочь людям, столкнувшимся с этой проблемой. Читатели узнают о перспективах выздоровления и важности комплексного подхода.
А что дальше? – [url=https://coream.ru/kogda-schyot-idyot-na-minuty-infuzionnaya-terapiya-protiv-tabletok-pri-ostrom-defitsite-zhidkosti]нарколог на дом[/url]
Excellent reminder to insulate pipes; Astar Air Conditioning, Plumbing & Electric exhibits the fundamentals at HVAC contractor near me .
College move season gets busy around Virginia Beach— Virginia Beach vehicle transport helped me lock a date ahead of the traffic.
This was a great article. Check out Roof repair near me for more.
You actually make it seem really easy with your presentation but I
find this topic to be actually one thing that I believe
I would never understand. It sort of feels too complicated and very wide for me.
I am taking a look forward on your next put up, I will
attempt to get the hold of it!
Güzellik ve bakım salonu önerileri konusunda Diyarbakır’da yeni açılan yerler var. Harita ve yorumlar Diyarbakır gece eskort ’da mevcut.
Weather in North Texas is unpredictable. I added floor protection and shrink-wrap based on recommendations from Local movers Dallas .
I have actually been looking for the best Gutters company near me and kept discovering multiple exceptional evaluations about A+ Gutters for Nocatee gutters
Me atendieron fuera de horario y solucionaron todo, gracias cerrajero de urgencias nocturno .
Clear breakdown of responsibilities. For tradies moving to QLD, the White Card Gold Coast requirement is essential—here’s a reliable place to enroll: Cannon Hill white card
Outstanding service every time with The Master’s Lawn & Pest! They’re hands down the best landscaping company in St Augustine. landscaping st augustine
For B2B explainer videos with no the bloat, strive Fast Hippo Media: AEO Frisco .
If your ceiling is sagging, don’t wait—name Emergency water damage restoration to evaluate structural dangers right this moment.
Quality service whenever with Pure Energy Electrical Services! They’re unquestionably the very best electrician near me in St Augustine.
electrician st augustine
I have actually been searching for a reputable Chiropractor near me in St Augustine and maintained seeing terrific evaluations regarding Pain Relief Centre chiropractor st augustine
First-timers: insurance coverage varies by carrier. I compared certificates and got clarity through Greensboro Auto Transport’s Works before signing.
В данной статье мы поговорим о будущем медицины, акцентируя внимание на прорывных разработках и их потенциале. Читатель узнает о новых подходах к лечению, роли искусственного интеллекта и возможностях персонализированной медицины.
Узнать больше > – [url=https://mediry.ru/cchto-takoe-kapelnicza-ot-zapoya/]clinica plus в костроме[/url]
Thanks for the great tips. Discover more at albergues privados Palas de Rei .
Prairieville Animal Hospital makes grooming stress-free for both pets and owners. Our cat’s coat is silky now. Link: spay neuter prairieville .
My card information synced quickly; scheduled and verified through white card training Gold Coast for white card Gold Coast.
The beard split-end solutions worked fast; trimmer and oil from vintage barbershop helped.
Loved the tip about MERV ratings— central ac repair helped me pick the right filter for airflow.
For students and first-time renters in Concord, Concord commercial movers offers rates that won’t wreck your wallet.
Rivera Tennis Academy tennis classes emphasize fundamentals plus match tactics—perfect balance showcased on tennis programs near me .