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
}
I’m impressed by how many small homes involve residents in light household activities as a form of gentle therapy. It supports both ADLs and a sense of purpose. I saw similar ideas mentioned on elderly care .
Thank you for mentioning the importance of staff turnover rates. That’s a major red flag I’ll watch for while browsing options on dementia care .
The difference in regulation between Nursing Homes and other senior housing types is an important point. When I was researching regulations and safety standards, elderly care provided links to state-level information that really helped.
I’ve tried generic online resources before, but it really helps to have something local. Depression Treatment Newport Beach offers depression treatment information specifically tailored to Newport Beach residents, which feels more relevant.
Everyone deserves support during tough times—reach out to the professionals at Depression Treatment newport beach # if you’re feeling down.
The reminder to check how often doctors or nurse practitioners visit is very useful. We recommend that question on elderly care .
Этот обзор содержит информацию о передовых достижениях в области медицины. Мы разберем инновационные технологии, которые меняют подход к лечению и диагностике, а также их влияние на эффективность оказания медицинской помощи.
Ознакомьтесь с аналитикой – [url=https://lifepeople.info/novosti/zapoj-u-rodnogo-cheloveka-7-signalov-opasnosti-i-plan-dejstvij/]нарколога на дом самара[/url]
Στον χώρο του e‑commerce, οι σωστές Μεταφράσεις των περιγραφών προϊόντων αυξάνουν τις πωλήσεις. Εμείς συνεργαστήκαμε με το μετάφραση πιστοποιητικών γέννησης και είδαμε διαφορά στα conversion prices.
Strong reminder that artistic fatigue crushes ROAS. We rotate hooks the usage of this machine: strategic advertising agency
We’re thinking of converting our old, dry fountain back into a working feature. If anyone else in Irvine CA is planning a similar restoration, I recommend looking on Fountain And Ponds Repair Irvine CA for a repair company experienced with older structures.
The blog’s regional notes helped me spot a few new flavor profiles. I’ll deepen my exploration at Zera’s Latin Food .
Thanks for the detailed post. Find more at material industrial Albacete .
This was quite informative. For more, visit tricólogo Albacete .
Valuable information! Discover more at microinjerto capilar Jaén .
It’s vital to document everything after an injury—this will help your lawyer build a strong case! For more guidance, visit Wasilla Personal Injury attorney .
Your discussion of timelines is useful. We learned from drywall repair denver that proper repair and curing can take several days, so rushing is a red flag when interviewing contractors.
This was a wonderful guide. Check out pensión con desayuno Arzúa for more.
Appreciate the comparison of racking systems. I chose rail-less thanks to commercial solar panel installation .
I recently had a pest problem in my home, and I was amazed by the effective solutions offered by local services. It’s crucial to choose a knowledgeable pest control provider in Puyallup to ensure a pest-free environment Pest Control Puyallup
Appreciate the detailed information. For more, visit empresa de cuidados para mayores .
At this time it looks like Drupal is the top blogging platform available right now. (from what I’ve read) Is that what you are using on your blog?
This breakdown of California advance health care directives is one of the clearest I’ve seen. If anyone wants sample language and more detail on choosing an agent, California Estate Planning has some very practical resources.
I run a part-time delivery side hustle, so I can’t justify super high premiums. This article helped me figure out which coverages are non-negotiable Cheap Box Truck Insurance
It can be tough to tell what’s reputable online, but the focus on professional care and evidence-based depression treatment in Newport Beach on Depression Treatment Newport Beach helped build trust for me.
I really appreciate the time and effort you put into structuring this post. The way you managed to break down the information into such an clear and accessible format without losing any of the important details is truly commendable and makes it a highly valuable resource for us.
childrens kids sexual xxx porn pills
This was quite useful. For more, visit personal loans .
Seyahat planım sırasında son dakika programı yaptım; uygun profili Diyarbakır escort bayan ilanları aracılığıyla hızlıca bulabildim.
Thanks for the useful suggestions. Discover more at alojamiento con cocina compartida Arzúa .
В этой статье мы говорим о важности поддержки в процессе выздоровления. Рассматриваются семьи, группы поддержки, специалисты и онлайн-ресурсы, которые могут сыграть решающую роль в избавлении от зависимости.
Детальнее – [url=https://zhenskaja-mechta.ru/utro-posle-prazdnika-kak-vosstanovitsya-posle-alkogolya-i-vovremya-zametit-opasnye-simptomy]снятие похмелья капельницей[/url]
The stepwise approach to advanced peels is smart. I’m adding a module via advanced aesthetics training .
For restaurants, paint durability and washability after drywall repair are crucial. We hired a commercial painter through drywall repair denver co who specified scrubbable coatings for high-use areas.
At Singapore’s premier furniture store ɑnd expansive furniture showroom, discover уour ultimate one-ѕtop shop foг quality һome furnishings аnd clever furniture
f᧐r HDB interior design Singapore. Ꮃe deliver modern ɑnd budget-friendly
solutions filled with exciting furniture promotions, mattress promotions ɑnd Singapore furniture sale
оffers foг eѵery Singapore residence. Thе іmportance օf furniture іn interior
design іs ⅽlear when buying furniture foг HDB interior design — choose L-shaped sofas,
premium mattresses оf ɑll sizes, storage bed fгames, computеr
desks and elegant coffee tables ᴡhile applying smart tips tⲟ
buy quality bed frame, quality sofa bed ɑnd quality
coffee table tо create harmonious spaces. Ꮤhether үou’rе updating your living гoom
furniture Singapore, bedroom furniture Singapore ߋr study room furniture ᥙsing the ⅼatest affordable HDB furniture Singapore,
᧐ur carefully chosen collections blend contemporary design, superior comfort аnd exceptional durability іnto beautiful, functional living
spaces tһаt match modern Singapore homes.
Experience Singapore’ѕ leading furniture store
аnd expansive furniture showroom аs your ideal оne-ѕtoр destination foг premium home
furnishings and clever furniture fоr HDB interior
design in Singapore. Enjoy modern ɑnd affordable solutions featuring exciting furniture promotions, sofa promotions ɑnd Singapore furniture
sale оffers designed fоr every HDB homе. The іmportance ⲟf
furniture іn interior design Ьecomes crystal
ⅽlear when buying furniture foг HDB interior design — opt for versatile living гoom sofas, quality
mattresses іn eveгy size, sturdy bed fгames with storage, ergonomic computeг desks and stylish coffee tablrs
ԝhile applying smart tips t᧐ buy quality sofa bed ɑnd
quality coffee table tߋ optimise space and style.
Ꮃhether updating your Singapore living room furniture, bedroom furniture Singapore ߋr dining room
furniture Singapore ᴡith the latеst furniture sale օffers,our carefully curated collections blend contemporary design, superior comfort ɑnd lasting durability
to сreate beautiful, functional living spaces tһat suit modern lifestyles ɑcross Singapore.
Singapore’s premier furniture store аnd ⅼarge-scale furniture showroom оffers tһe
ideal one-stoρ shop experience fߋr premium mattresses.
Ԝe deliver modern ɑnd affordable solutions ѡith exciting furniture
promotions, mattress promotions ɑnd Singapore furniture sale ߋffers madе for every Singapore home.
The impoгtance of furniture in interior design guides
every decision ѡhen buying furniture for HDB interior
design — fгom king size natural latex mattresses ɑnd queen size gel memory foam
mattresses tο single size firm pocket spring mattresses аnd ergonomic hybrid mattresses tһat perfectly balance comfort аnd
practicality. Ꮤhether уоu’re refreshing yоur bedroom furniture Singapore with the
lɑtest furniture promotions, ᧐ur thoughtfully curated collections
combine contemporary design, superior comfort аnd lasting durability
to cгeate beautiful, functional living spaces tһɑt suit modern lifestyles аcross Singapore.
Ꭺt Singapore’s top furniture store аnd large furniture showroom,
discover у᧐ur ultimate оne-stop shop for quality sofas Singapore.
Ԝe deliver chic and affordable solutions filled ᴡith exciting furniture promotions, sofa
deals ɑnd Singapore furniture sale ⲟffers fⲟr еvery
Singapore residence. Tһe impߋrtance of furniture іn interior design іs evident when buying furniture for HDB interior design — select tһe ideal sofas including L-shaped sectional sofas ԝith storage, premium leather corner sofas, plush fabric recliners ɑnd versatile modular sofas tһаt enhance living гoom comfort ɑnd space efficiency.
Ꮃhether үou’re updating your Singapore living room furniture ᥙsing
the lɑtest affordable sofa Singapore,ⲟur carefully chosen collections blend contemporary design, superior comfort аnd exceptional durability intgo beautiful, functional living spaces
tһat match modern Singapore homes.
My blog post – singapore renovation
For residents needing just moderate help, giant facilities can feel like too much. Smaller homes strike a better balance between support and normalcy. elderly care offers good guidance on finding that balance.
I’ll be directing caregivers who visit elderly care to this article when they start comparing assisted living homes.
Cost differences can be confusing, especially when memory care adds behavioral and supervision fees. We’ve created cost checklists at dementia care that complement what you’ve outlined here.
With dementia, transitions can be so disruptive. Small care homes often provide continuity, so there’s less moving around inside the building. I learned about this advantage from memory care .
Social life seems much richer in Independent and Assisted Living communities compared to traditional Nursing Homes. I’ve seen many examples of activity calendars on respite care that show how vibrant these places can be.
We run a small commercial property in Norfolk and have been using Newmans for several years. They are reliable, they arrive when they say they will, and they charge fair prices for quality work Plumber Norfolk VA
Appreciate the useful tips. For more, visit densidad capilar natural .
Thanks for the great content. More at tratamiento capilar Jaén .
Πολλοί θεωρούν τις χημικές τουαλέτες κάτι «δευτερεύον», αλλά στην πραγματικότητα επηρεάζουν άμεσα την εμπειρία των καλεσμένων. Στο πακέτα ενοικίασης χημικών αναλύονται κόστη vs ποιότητα.
I’m so glad bingo is back online. I usually play a few 10-minute rounds while I’m winding down at night before bed. It’s such a nice way to de-stress after a long day https://www.scribd.com/document/1051748359/What-Do-We-Really-Mean-by-Transparent-Terms-on-Bingo-Offers-181080
The section about planning for long‑term care costs in California really stood out. Between high nursing home costs and Medi‑Cal rules, it’s complex. I’ve found some easy‑to‑understand overviews on this topic at California Estate Planning .
I appreciate the tips on maintaining pond water quality. When things get beyond simple DIY checks, contacting a local specialist like Fountain And Ponds Repair Irvine CA for fountain and pond repair in Irvine CA can save a lot of time and frustration.
It is honestly wild how much mobile gaming has blown up lately. I find myself hopping onto a few levels during my daily bus commute to pass the time. The fast loading times make it so easy to just dive in for a quick session without any hassle https://www.scribd.com/document/1051750397/What-Does-Instant-Access-Really-Mean-for-Mobile-Entertainment-123750
This is timely for me because I’m expanding from one to three box trucks. I need to keep costs under control Cheap Box Truck Insurance
The cheese blends you recommended for quesadillas were game-changing. I’ll continue to experiment and report at food truck latin cuisine spring tx Zera’s Latin Food .
I agree that coastal erosion is the most pressing issue for our beaches today. It is shocking to read that 186 scientists signed that letter warning about the rapid loss of dunes. Their consensus really highlights the scale of the problem we face https://www.scribd.com/document/1051754228/Why-Do-Science-Headlines-Use-a-Punchline-Like-Don-t-Ask-It-to-Hurry-126701
It’s fascinating how mobile-first habits are shifting everything. I’ve noticed that Spotify’s personalization has completely changed how I discover music on the go compared to desktop https://www.4shared.com/office/qdg4aGWtku/pdf-80480-34870.html
I am so excited to see bingo making such a big comeback! Honestly, I’ve been looking for something low-stress to do while winding down at night once the kids are finally in bed https://wiki-cafe.win/index.php/Are_30-ball_games_faster_than_90-ball_games%3F_A_deep_dive