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
}
If you’re in Naples FL and need quick cash for a non-running car, I had a great experience getting a same-day quote here: we buy junk cars Naples FL .
Giao dịch tự động và an toàn trên iwin, bắt đầu tại cổng game iwin
Love how these commercial rollup doors cut drafts in winter. Strongly recommend: roll up shutter repair Joliet
Shops should blue-check splines for contact pattern when rebuilding; I learned to ask thanks to drivelines .
Great note about undercoating removal— surface preparation services used the right media without warping panels.
Tight timelines? Ask about guaranteed arrival windows, not “morning/afternoon.” I filtered for punctuality ratings on Cheap movers Grand Rapids .
Nạp tiền tiện lợi bằng nhiều cổng trên hitclub .
For correct insurance claims taking care of and also receptive help, BSA Claims is actually unbeatable amongst independent adjusters. A lot more at flood adjuster Fort Myers .
By incorporating Singaporean contexts іnto lessons, OMT makes
mathematics ɑppropriate, promoting affection ɑnd motivation fоr high-stakes
examinations.
Expand уour horizons with OMT’s upcoming brand-new physical space ߋpening in September 2025, providing a lot morе
chances for hands-on mathematics exploration.
Wіth trainees in Singapore starting official mathematics education fгom day
one and dealing with high-stakes evaluations, math tuition ρrovides the additional edge
required tо accomplish top performance in thіs crucial topic.
Ԝith PSLE mathematics developing tⲟ consist of morе interdisciplinary aspects, tuition ҝeeps students updated
on incorporated questions mixing math ᴡith science contexts.
By usіng substantial exercise ѡith prеvious O Level papers, tuition outfits students ѡith familiarity аnd thе capacity to prepare for inquiry patterns.
Inevitably, junior college math tuition іs vital to safeguarding tор A Level гesults,
opеning doors to distinguished scholarships аnd hiɡһeг education and learning possibilities.
Distinct fгom оthers, OMT’s curriculum enhances MOE’ѕ through a concentrate on resilience-building exercises,
aiding students deal ᴡith tough troubles.
The self-paced e-learning platform from OMT is vеry flexible lor, making іt less complicated to handle
school аnd tuition for greater mathematics marks.
Math tuition assists Singapore students ցet rid of usual pitfalls
іn computations, bring about fewer careless mistakes іn tests.
Have a loοk at my site :: math tuition singapore
If you’re moving out of a steep Lakeside driveway, mention it— Johns Creek Mover’s arranged a smaller box truck to shuttle to the tractor-trailer.
If quality concerns in independent adjusting, BSA Cases is actually the very best in the business. More information at BSA Claims Solutions independent insurance adjuster fort myers, .
Helpful discussion here. I’d add that in California, the rules can differ depending on whether the claim is against your own insurer or the at‑fault driver’s insurer. A loss of value claims lawyer, like the ones at experienced loss of value attorney , can sort that out.
In the end, I choose a power washing company based on a mix of reputation, clear communication, detailed services, and proper insurance. Using resources like Power Washing Arlington VA has made it much easier to sort out the pros from the amateurs.
Your explanation of how utility potholing supports SUE (Subsurface Utility Engineering) is really helpful. We’ll be adding OC utility potholing contractors to our list of recommended Orange County field investigation services.
Статья о методах прокачки персонажа
[url=https://vita63.ru]смотреть секс с игрушками[/url]
узнать больше Здесь [url=https://retrocasino-mobile.com]newretrocasino[/url]
It’s useful to know that professional plumbers handle both repairs and installations, from toilets and sinks to whole piping systems. I’m planning a few upgrades and will likely reach out to affordable emergency plumbing services .
This was a fantastic read. Check out Paver Cleaning Commack, NY for more.
Loft Conversion Harold Wood Colin Cameron Personal Involvement
Colin was personally involved in the project from start to finish, which is something I had not experienced with building contractors before Loft Conversion Near Me
For seniors at risk of isolation, a small home makes it more likely they’ll be invited into conversation while getting assistance with meals or grooming. assisted living has some thoughtful content on this.
I love the idea of instant access, but my experience has been frustratingly laggy whenever I try to stream anything in high quality. It feels like the technology isn’t quite there for reliable sessions yet real-time interaction apps
I honestly think gamification strategies like points and badges miss the mark for professional teams. They distract us rather than bringing the group together Have a peek at this website
I’ve definitely noticed how much more engaging mobile casinos have become lately. Honestly, the shift toward live dealers has been a game-changer for me. It feels so much more authentic than just staring at a static screen https://wiki-quicky.win/index.php/What_Internet_Speed_Do_I_Need_for_HD_Live_Casino_Streaming%3F
For arborist-certified care, finding a licensed crew matters. See trusted options at tree service .
пояснения [url=https://retrocasino-mobile.com]newretrocasino[/url]
I need proof of valuation coverage beyond basic. What moving insurance options does Columbia Heights movers offer for Columbia Heights moves?
Valuable information! Find more at luxury kitchen remodel .
Good reminder to ask about staff training and turnover. I’ll add this as a key evaluation point on my site assisted living .
I have been stuck in this reCAPTCHA loop for days whenever I try to access certain sites while using my Brave browser. It is incredibly frustrating to get that Enterprise quota error constantly recaptcha verification
This post provides such important information. Check out dentist Jacksonville FL for all things dental care!
I have seen this work well, but it is tricky to get right without feeling like spam Find more info
I really appreciate how much easier digital entertainment has become lately. My biggest struggle used to be dealing with constantly laggy streams during live events, which was so frustrating More helpful hints
I really enjoy how this article links entertainment to our current office setup. Using points and badges definitely helps keep remote teams motivated during long weeks. However, we should remember that over-gamifying tasks can sometimes feel patronizing Learn more
Price matters, but I’ve started to focus more on safety and proper equipment when choosing a power washing company. The cheap guys sometimes use too much pressure and cause damage. That’s why I’m leaning toward using Pressure Washing Arlington VA this season.
I’ve really noticed how much more immersive these mobile sites have become lately. Personally, the inclusion of live dealers makes a huge difference for me; it actually feels like you’re sitting at a real table instead of just staring at a static screen https://codysdui093.iamarrows.com/what-makes-a-casino-app-feel-interactive-instead-of-static
I appreciate how you highlighted staff training as a major difference. Memory care caregivers are usually trained in dementia behaviors, which can be essential. We share similar insights on memory care .
I really enjoyed this perspective on how we connect online. The live chat feature during our weekly gaming sessions with friends has completely changed how we experience these platforms https://wiki-triod.win/index.php/How_Multiplayer_Systems_Increase_Engagement:_The_New_Anatomy_of_Retention
Great breakdown of the mobile interface. I agree that navigation is key, but I feel like the biggest frustration for most of us is withdrawal speed betting app navigation
I definitely like how precious jewelry can transform a whole outfit! It’s fantastic how a simple piece can include so much beauty and character. Have you ever thought about tailoring your own jewelry? It can produce a really special declaration piece buy gold
The home-like feel of a small senior care home makes a huge difference in how comfortable older adults feel asking for help with personal care. That’s why I appreciate what elderly care is promoting.
I’ve been dealing with those endless verification loops for weeks, and it’s honestly driving me crazy. Every time I turn on my VPN, the site immediately flags me for exceeding the enterprise quota https://emilioezho292.theglensecret.com/what-extensions-commonly-break-recaptcha-verification
We picked eco-friendly units after reading portable toilets ’s guide to green restroom options.
I really enjoyed reading this take on digital entertainment. Honestly, the biggest hurdle for me lately has been dealing with constant laggy streams when I’m trying to catch a show on the go https://www.protopage.com/hannah_kelly01#Bookmarks
Really interesting perspective on borrowing mechanics from games. I’ve seen this work well for productivity apps, but the risk is always annoying users with too many notifications Check out the post right here
I found the point about streaks really interesting. While they definitely keep me coming back to apps like Duolingo, I sometimes feel like I am just performing for the algorithm rather than actually enjoying the content real-time feedback loops
It is interesting to see the growth in mobile gaming, but I honestly find that some apps still have really clunky onboarding processes. It can be quite frustrating when you just want to get started but have to navigate endless registration screens quick casino games for busy parents
I really enjoyed this piece on how entertainment concepts reshape our remote work lives. Using “points and badges” to foster friendly competition definitely keeps our team motivated during long projects managing distractions in attention economy
I’ve been playing on mobile for a while, and honestly, the shift toward live dealers has completely changed the experience for me. It feels so much more social than just clicking a button against a computer manage push notifications casino app
I really enjoyed reading your take on online engagement. Personally, I find that the live chat feature is a total game changer when I am gaming with friends late at night. It makes everything feel so much more connected even when we are miles apart https://chancevwpt210.wpsuo.com/how-do-interactive-features-affect-user-satisfaction
After hurricane season, my flooded car was totaled. sell my junk car for cash lehigh acres fl still bought it and properly reported it as salvage.