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
}
This was such a fascinating read on how the built environment dictates the flow of a workspace. I have always felt that the addition of skylights completely changes the mood of an office by bringing in that natural rhythm of the day maximizing natural light in offices
Dealing with this lingering knee injury has me scouring clinics, but your point about the importance of a sterile environment really hit home https://www.protopage.com/george-flores01#Bookmarks
It’s great to see Japan moving forward with crypto integration for online platforms. I’ve personally started sticking to stablecoins for these transactions to avoid the headache of price volatility during checkout crypto user protection japan laws
mostbet crash коэффициенты [url=http://mostbet52746.help/]http://mostbet52746.help/[/url]
We’ve been debating getting panels fitted for months now because our energy bills are just getting out of hand. The idea of a battery pushing self-consumption up to 80% sounds like a total game-changer for a family of four Helpful resources
Do Texas courts consider victim input more heavily when deciding between probation and deferred adjudication? Court practice at assault lawyer .
This is such a helpful breakdown of how to keep local listings clean. I recently spent hours dealing with duplicate listings that were tanking our SEO, so I definitely relate to the frustration directory management
I really enjoyed your perspective on how the bones of a building influence the interior experience. I have always been fascinated by how architects use high ceilings to make a cramped retail space feel completely open and inviting floor plan efficiency metrics
I’ve been eyeing a trip to Charleston for a while now, and seeing that Angel Oak stop mentioned just confirmed I need to make it happen this spring. It looks like the perfect spot to stretch the legs after a long day of riding Southern Comfort yacht Charleston
melbet ставки на баскетбол [url=www.melbet53847.help]melbet ставки на баскетбол[/url]
mostbet kupon kod [url=www.mostbet04826.help]www.mostbet04826.help[/url]
If your dog hates rain, short incentive walks help; scheduled on weekly dog walking service Chandler .
pin up koeffitsiyentlar [url=https://www.pinup41537.help]pin up koeffitsiyentlar[/url]
I really enjoyed how this piece explained the link between structure and workflow. I have always been fascinated by how architects use atriums to create a sense of community in large office buildings sustainable flooring for high traffic
Every state has different laws regarding auto accidents; make sure you’re informed by visiting Accident Lawyer .
This was such a thought-provoking piece on how structural elements dictate the flow of a workspace https://www.mapleprimes.com/users/philip-morgan06
I appreciate the section on lost wages and future earnings. Truck Accident Attorney includes a calculation guide.
Хороший гайд для тех, кто хочет разобраться в продвижении сайтов в 2026 году. Автор делает акцент на том, что SEO остаётся основой устойчивого присутствия в интернете, несмотря на развитие платных каналов. Разбирает ключевые направления: анализ ключевых слов, контент-оптимизацию, техническое SEO, внешние сигналы и пользовательский опыт. Есть блок про типичные ошибки и интеграцию SEO с другими инструментами интернет-маркетинга. Полезно: https://drivetvchannel.ru/stati/prodvizhenie-sajtov-v-2026-godu-polnyj-gajd-po-seo-i-internet-marketingu/
I appreciate the focus on durability. professional screen repair service recommended the right mesh for our windy area.
мостбет вывести деньги 2026 [url=https://mostbet52746.help/]https://mostbet52746.help/[/url]
Thanks for covering fall prevention. We used senior care to compare safety assessments and emergency response protocols.
This was such an interesting read on how architectural bones dictate the flow of a workspace. I have always wondered how much impact those massive floor to ceiling glass walls actually have on employee productivity versus just looking nice atrium lighting design tips
Terrific pointer to inquire about staffing ratios. senior care gives insights on caretaker availability and certifications.
Thanks for the detailed post. Find more at reserva alojamiento Arzúa .
Financial assistance options are confusing. assisted living explains veterans’ benefits, long-term care insurance, and more.
Thanks for the thorough article. Find more at apartamento turístico Arzúa .
This was very well put together. Discover more at campamentos urbanos .
Thanks for the helpful advice. Discover more at senior care .
1win игровые автоматы [url=https://1win71849.help/]https://1win71849.help/[/url]
Motorcycle collisions have unique bias issues; Motorcycle Accident Attorney offers strategies to counter them.
Excellent after-hours locksmith provider in Orlando offered by way of Orlando Florida locksmith Unit .
I enjoyed this article. Check out Garaginization LLC for more.
Good explanation. Bus Accident Lawyer explains when punitive damages may apply in DUI crash cases.
I found this very interesting. For more, visit Garaginization LLC .
Cultural and language compatibility matters. We located multilingual staff options via senior care .
If you’re evaluating contractor bids, add frame to finish to your shortlist.
I found this very interesting. Check out Garaginization Inc for more.
I enjoyed this post. For additional info, visit habitaciones con baño privado .
For high-angle setups, consider double-cardan with correct centering kit; I confirmed specs via drivelines .
I appreciate your point about combining treatments wisely. I got a basic roadmap from botox before consulting. botox NY
Great breakdown. One thing I’d add for anyone starting out is to check if the host offers automated daily backups that are easy to restore yourself. I’ve learnt the hard way that relying on a manual process is a massive risk when things go wrong best hosting for high traffic blogs
Thoroughly enjoyed this post! It’s essential reading for anyone involved in vehicle collisions—don’t forget to check out Auto Accident Attorney #.
fast horse racing results for today
Feel free to visit my blog post greyhound derby 2nd round draw (Richelle)
Oh my goodness! Amazing article dude! Many thanks, However
I am experiencing problems with your RSS. I don’t understand
why I am unable to join it. Is there anyone else having identical RSS issues?
Anyone who knows the answer can you kindly respond?
Thanx!!
Great breakdown of the options. I’d add that before committing to a provider, it’s always worth checking if they offer automated daily backups as part of the base plan Website link
In our hotel kitchen, nightly floor scraping plus dry-wipe before wash-down keeps FOG out of drains. We trained with a short video from Grease Trap Pumping .
I learned a lot about abrasive types— mobile blasting solutions helped us pick glass vs garnet.
I like the idea of drawing a scene diagram. Car Accident includes a printable crash diagram sheet.
Great article, thanks for the breakdown. One thing I’d suggest adding is checking if they offer daily off-site backups as standard. I’ve learnt the hard way that relying on a host’s internal backup isn’t always enough when things go sideways Great post to read
Ceiling fan remote kits simplified my setup. Install help at aluminum wiring repair and pigtailing .