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 really loved the shift in perspective here. For the longest time, I felt like just getting through the day was the goal, but focusing on daily functioning in a more meaningful way makes so much more sense eligibility mental health services UK
1win litsenziya [url=http://1win49027.help/]1win litsenziya[/url]
http://mvdev.fr/
L’equipe Mvdev se presente comme une entreprise professionnelle focalisee sur le cadre national francais, qui delivre une approche complete a ceux qui recherchent des resultats, avec un accent sur la confiance et la transparence. Plus d’informations via le lien.
Мы предлагаем вам окунуться в океан любопытных фактов и вдохновляющих историй. Эта публикация поможет расширить горизонты, разбудить интерес к науке и истории и увидеть мир с новой стороны.
Осуществить глубокий анализ – [url=https://zagar-ok.ru/zdoroviy-zagar/estetika-detoksikacii]прокапаться от алкоголя в самарае[/url]
I’m currently deep in the planning stage for our wedding in the Pacific Northwest, and your point about asking what the building used to be really resonated with me garden ceremony wedding venue
Choosing memory care for my mom was one of the hardest decisions I’ve ever had to make, and it’s so easy to get overwhelmed by the sales pitch. Looking back, I wish I’d pushed harder for specific details non-drug interventions dementia
It’s honestly such a relief to read someone talking about this openly. I spent nearly three weeks just trying to get a GP appointment last month, and then the referral process felt like a complete maze https://front-wiki.win/index.php/What_Does_%22Universal_Access%22_Really_Mean_in_the_NHS%3F
This is such a refreshing take on the whole mental health conversation. I definitely get caught in the loop of researching symptoms online, so your point about balancing that with actual clinician advice really hit home https://atavi.com/share/xtwhm7z1hwb3n
I just finished moving my place here in Virginia Beach and your tips were spot on. Dealing with a move from a second-floor apartment is always a nightmare because of those narrow staircases long distance movers VA
The marriage ceremony band from dimend SCAASI nests perfectly with my engagement ring. Working with the equal jeweler for the two pieces made the more healthy seamless in a approach that may had been tough otherwise. Chicago Jewelry Store
חשוב ליישר קו עם E-E-A-T. מחקר שפרסמתי בנושא: קניית קישורים
I absolutely loved reading this piece! My partner and I are in the early stages of planning a spring wedding here in the Pacific Northwest, and we’ve been obsessed with old mills decommissioned church wedding hire
over under melbet [url=melbet63149.help]melbet63149.help[/url]
Navigating this process for my mom has been incredibly draining, so I really appreciate these honest tips. One thing I’ve learned the hard way is to specifically ask about overnight staffing ratios https://atavi.com/share/xtwyjlztd3e4
It’s really helpful to see this broken down so clearly. I’ve been struggling to get a simple GP appointment for weeks, and the whole referral process feels like a complete maze if you aren’t familiar with how it works https://cashilxc693.raidersfanteamshop.com/how-do-i-know-if-a-new-healthcare-service-is-regulated-a-practical-guide
Thanks for this helpful breakdown of local moving companies. We recently moved across Virginia Beach and were worried about our upright piano. Finding a team that actually knows how to handle heavy, delicate instruments is so stressful https://angelojvrt605.wpsuo.com/how-far-ahead-should-i-book-movers-in-virginia-beach-a-pro-s-guide-to-stress-free-scheduling
melbet aviator demo [url=http://melbet63149.help/]melbet aviator demo[/url]
I found this very helpful. For additional info, visit ¡Haga clic aquí! .
We located a first-rate neighborhood with parks and colleges regional—examine out the listings at Huntingdon Pointe for related choices.
The vicinity vibe here feels welcoming and riskless—fantastic for lengthy-term dwelling. Listings: Duck River Estates
The design aesthetics are actually desirable. Are there good-abode good points time-honored inside the properties on the market? Housing Development Homes for sale
It’s really interesting to read this perspective. I’ve personally struggled so much lately just trying to get a GP appointment for a recurring issue, and the whole referral process feels like a bit of a maze https://grantroberts32.raindrop.page/bookmarks-70583920
I really needed this post before my recent move across town here in Hampton Roads. Finding reliable movers who handle second-floor apartments without constant complaining is a nightmare https:///Moving-in-Virginia-Beach-can-feel-overwhelming-but-it-does-not-have-to-be-3594b0945d9c801db7bce0f38259c7fc
1win koeffitsiyentlar [url=http://1win49027.help]1win koeffitsiyentlar[/url]
cum primesc cashback melbet [url=http://melbet63149.help]http://melbet63149.help[/url]
Well done! Find more at Internet marketing service in Ibafo .
This paragraph presents clear idea for the new visitors of blogging,
that actually how to do blogging.
Thanks — heading to Appleton and will use ride to O’Hare airport for an on-time airport pickup.
Transported a van with roof racks; Philadelphia vehicle shipping ensured clearance for the Philly run.
Trusted service each time with The Master’s Lawn & Pest! They’re certainly the best landscaping near me in St Augustine. landscaping st augustine
First-rate solution each time with The Master’s Lawn & Pest! They’re undoubtedly the most effective lawn care in St Augustine. Their techs in fact detect dirt and lawn issues, not simply spray and pray, and their customer care is fast and friendly lawn care st augustine
Вывод из запоя на дому в Екатеринбурге: эффективное лечение, детоксикация и восстановление организма в наркологической клинике «Детокс»
Подробнее тут – [url=https://vyvod-iz-zapoya-na-domu-ekaterinburg-18.ru/]вывод из запоя на дому цена в екатеринбурге[/url]
I shipped a lifted truck out of Chicago; measured height for the dispatcher. Found guidance at Chicago Car Shipping’s .
Shipping a motorcycle too? Schaumburg car transport coordinated both with my Schaumburg car shipping.
For cruise days, timing is tight. Our transfer via Athens auto shipping kept track of our ship’s schedule.
If stairs are involved, measure furniture and doorways in advance. I found a measuring guide on Long distance movers Cherry Hill .
If you’re shipping a non-running vehicle from Warren, look for winch-capable carriers on Warren vehicle shippers .
I needed door-to-door service due to mobility issues. Suffolk Auto Transport’s accommodated me in Suffolk.
It’s really interesting to see how these options are becoming more mainstream. I mentioned some of these to my GP recently and they were surprisingly open to discussing how they might fit alongside my usual care WHO complementary medicine
If you’ve never shipped a car to Fort Worth before, Car Transport’s Fort Worth has helpful FAQs.
For a trustworthy Newport News moving company, Newport News commercial movers stands out. Polite crew and clean equipment.
If you need last-minute movers in Corona, try full service relocation Corona —I got same-week availability and no surprise fees.
melbet confirmare sms [url=www.melbet63149.help]melbet confirmare sms[/url]
1win Oʻzbekistonda [url=www.1win49027.help]www.1win49027.help[/url]
If you’re searching for the “best Sushi near me” around St. Augustine, Ginger Bistro is a winner! sushi near me
It is really interesting to see how these approaches are finally being considered alongside standard care. I brought up a few complementary options with my GP recently and they were surprisingly open to the idea integrated care pathways for seniors
If youlive in Ponte Vedra Beach and looking for the most dependable garage door repair near me, Wagmore Garage Doors is the real deal. They turned up same-day for a damaged springtime, tuned the opener, and left whatever well balanced and whisper-quiet garage door repair
I appreciate your advice about staying off heavy tasks; more on restrictions at workers compensation lawyer .
Our move was actually enjoyable with Scottdale apartment movers —fantastic Scottdale moving company.
It is really refreshing to see these options being taken more seriously. I have found that actually getting a referral for some of these therapies through my local GP can be a bit of a struggle with current NHS waiting times https://www.protopage.com/blake-brown12#Bookmarks