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
}
It is interesting to see the shift toward a more casual experience. I worry that blurring the lines between gaming and gambling makes it harder to stay responsible Go to this site
It’s interesting to see how the industry is evolving since the IGRA 1988 framework was first established random number generator casino
That piece on the psychology of online casinos was eye-opening. I particularly liked the point about frictionless signup; as a small business owner, I often overcomplicate my onboarding process, hurting conversion rates compliance frameworks for global business
I enjoyed reading about combination facials (like adding LED or masks) at Las Vegas spas on Facial Treatments Las Vegas .
The natural style used throughout this post makes the content feel more authentic and approachable, which helps readers stay interested and encourages them to participate in the discussion more openly and respectfully.
在线购买大麻用于XXX成人色情视频
Этот обзор медицинских исследований собрал самое важное из последних публикаций в области медицины. Мы проанализировали ключевые находки и представили их в доступной форме, чтобы читатели могли легко ориентироваться в актуальных темах. Этот материал станет отличным подспорьем для изучения медицины.
Хочу знать больше – [url=https://lucky-woman.com/effektivnyye-sposoby-bystro-izbavitsya-ot-pokhmelya-i-vosstanovit-sily.html]Психиатр на дом в Химках[/url]
This article really hit home for me. I struggle so much with productivity guilt, especially lately while trying to balance full-time work and chasing after an energetic toddler digital downtime
This piece really clicked for me. I always wondered why I keep playing games with so much random loot. It makes sense that it is about agency through participation randomness vs skill in games
If you’re nervous about court, ask a Maryland divorce lawyer from Divorce Lawyer In Maryland whether your case can be settled through negotiation or mediation.
Excited about adding some new decorations around the newly opened swimming area this summer ! # # anyKeyWord ## pool opening
I really appreciated this perspective! I’m definitely guilty of reaching for my phone while waiting for my morning coffee at the local shop Helpful resources
I totally get this. The fluctuating range anxiety is real. Yesterday, the plummeting temperature wiped about 20 miles off my estimated range in just a few minutes of driving interactive platform design
Thanks for sharing your thoughts. I really appreciate your efforts and
I will be waiting for your next post thanks once again.
It is honestly refreshing to see these retro games making a comeback. There is something about that pure nostalgia that today’s bloated AAA titles just cannot capture themed bingo rooms
It is fascinating how buildings are evolving to become part of the show itself. I found the section on using circulation as story pacing particularly insightful, as it completely changes how guests move through an environment virtual reality environments for architectural visualization
It is really interesting to see how these apps are shifting towards a more gamified experience. It definitely feels less like traditional gambling and more like mobile gaming now self exclusion app
Tribal gaming has come a long way since IGRA 1988 was first signed. It’s interesting to see how the expansion into online platforms is being handled, especially regarding player safety tools like self-exclusion how to use self-exclusion
Man, the day after a big game is always the best. I spent the whole morning watching highlights on repeat and obsessing over the latest standings in the group chat with my mates https://wiki-nest.win/index.php/Gaming_After_Practice:_Is_It_Actually_the_New_Recovery_Standard%3F
I really appreciate the focus on frictionless signup in this piece. As a small business owner, I often struggle with wanting to get users into our platform quickly while still needing to qualify them properly Find out more
Searching for a Comprehensive Estate Planning Attorney Near Me? This firm provides clear roadmaps for executors and beneficiaries—see Comprehensive Estate Planning Attorney Near Me .
This really hit home for me. I’ve been struggling so much lately with productivity guilt; whenever I sit down to read or just relax after a long day of work stress, a little voice in the back of my head tells me I’m wasting time attention fatigue
This piece really clicked for me. I always wondered why I keep playing games with so much random loot. It makes sense that it is about agency through participation Get more information
During our Los Angeles home inspection near Sinclair Gas Station on N Broadway, the inspector flagged Emergency Plumber concerns plumber near me open now
I really appreciate this perspective. It’s so stressful when the estimated range drops suddenly on a long motorway trip statistical probability in route planning
I totally get this. I usually find myself scrolling through those short videos while waiting for my morning coffee at the local shop, and it really ruins my focus for the rest of the day https://front-wiki.win/index.php/Why_I%E2%80%99m_Choosing_Micro-Entertainment_Over_Marathon_Viewing
Honestly, it is so refreshing to see these retro titles making a comeback. There is just something about the old-school pixel art and simple mechanics that hits home https://gunnerawsh736.cavandoragh.org/why-does-bingo-keep-showing-up-in-modern-gaming-conversations
For deep cleanings and perio care in Plano, I trusted dentist plano .
Appreciate the comprehensive advice. For more, visit Ryze Outdoor Creations .
Wrongful death claims after a fatal crash require compassionate counsel; find help at car accident lawyer .
Gentle, repetitive strokes are soothing and effective. Technique overview at lymphatic drainage massage winnipeg .
This is such a fascinating take on how built space influences our immersion. I found the section on circulation as story pacing particularly insightful, as it really highlights how movement shapes the narrative flow https://pastelink.net/bt9ihorz
It’s really interesting to see how the landscape is shifting. I’ve always appreciated how many tribal operations evolved from simple gaming halls into full-scale destination resorts by adding hotels and conference centers to boost their local economies https://codysdui093.iamarrows.com/online-casino-platforms-vs-casino-resorts-what-is-the-real-difference
I really enjoyed this perspective on what mainstream businesses can learn from the gaming industry. The focus on frictionless signup is something I struggle with for my own site, as I worry about conversion versus security profitable home based online business
It is interesting to see these apps shifting toward a more casual experience because they do feel a lot like standard mobile games now. My main concern is how easy it is to lose track of time Learn more
Your suggestion to avoid heavy meals right before sessions helped. I learned that tip at body contouring .
Honestly, the day after a game is always the best part of being a fan. I usually spend my whole morning coffee break re-watching highlights from the London Lions game and texting my group chat to argue about the referee calls https://dominicksniceop-ed.cavandoragh.org/the-bbraun-sheffield-sharks-more-than-just-a-sponsor-name
This article really resonated with me, especially the section on productivity guilt https://telegra.ph/How-to-Actually-Switch-Off-Your-Mind-When-the-Workday-Wont-Quit-06-15
I never thought about why I get so hooked on these mechanics before reading this piece. It makes total sense that having agency through participation is what keeps me coming back for more habit forming app design
I’ve definitely experienced the range anxiety when those numbers start dropping unexpectedly. Dealing with a sudden cold snap really drains the battery way faster than the dashboard predicts https://zaneznae304.lucialpiazzale.com/does-driving-style-really-change-ev-range-as-much-as-people-say
I totally get this. Every morning while I’m waiting for my coffee at the corner shop, I catch myself mindlessly scrolling Additional reading
I appreciated this post. Check out pensión familiar en Arzúa for more.
Before spending money on an expensive hotel spa, read the comparisons on Facial Treatments Las Vegas about facial treatments in Las Vegas.
Honestly, it is refreshing to see these old-school titles making a comeback. There is something about that pure, pixelated nostalgia that modern high-budget games just cannot replicate for me Find more info
I really enjoyed this perspective on how physical spaces influence the way we consume stories. It’s fascinating how architects are now using circulation as story pacing to guide our journey through an exhibit https://pixabay.com/users/56321916/
It’s fascinating to see how the landscape has shifted since the IGRA of 1988. While tribal resorts have done a great job diversifying their revenue with massive hotel and conference centers, the move into online gaming is definitely the next big hurdle https://escatter11.fullerton.edu/nfs/show_user.php?userid=9808778
As a novice dog parent, I’m investigating daycare choices that prioritize enrichment. This post helped! I’ll be bookmarking dog daycare near me to compare programs near me.
I always find myself obsessively checking the standings the morning after a big game. My group chat is non-stop debating those refs and missed calls https://alananderson8526.gumroad.com/
I really appreciated the distinction you drew between interactive and passive leisure Extra resources
The rationalization of acceptable roof pitch and material choice become on element. We run via those calculations on every new install task at Gikas Roofers roofing .
I have always wondered why I keep playing games with random loot drops, and this article finally explains it. The concept of structured uncertainty makes total sense. I think the reason it is so addictive is the agency through participation why we crave digital rewards