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’ve been experimenting with Rapid Indexer VIP recently to speed up my workflows. It’s hitting about an 89% success rate, which is decent, but it’s no silver bullet. I’m still seeing plenty of pages hit the ‘crawled – currently not indexed’ status in GSC how to use url inspection api
As a former gymnast, I’m picky about coaching quality, and san diego gymnastics rancho bernardo looks like one of the stronger options in the Rancho Bernardo / San Diego area.
I’ve seen this cause so much stress for directors lately. It’s a vital reminder that the 21-day clock starts from the issue date on the notice, not when you happen to pick it up from your mailbox https://echo-wiki.win/index.php/What_does_a_lockdown_Director_Penalty_Notice_actually_change_for_directors%3F
As a frequent flyer, the stand-upright test is usually the first thing I check before buying a new bag. It drives me crazy when my briefcase flops over in the terminal professional briefcase with laptop compartment
I found this article really helpful. We recently got a French Bulldog and realized pretty quickly how expensive they can be dog insurance for pre-existing conditions uk
My spaniel’s insurance renewal is coming up soon, so this guide is very timely. I have been leaning towards Tesco Bank because the Clubcard savings could really help offset the premium costs https://page-wiki.win/index.php/Which_UK_Pet_Insurer_is_Best_for_First-Time_Pet_Owners%3F_(Hint:_Stop_Searching_for_%22The_Best%22)
Stopped by for a casual meal and enjoyed the overall atmosphere and flavors offered. latin food Spring TX
888satrz [url=www.888starz-uz1.org/]www.888starz-uz1.org/[/url] .
888 starz [url=888starz-egypt9.com]https://888starz-egypt9.com/[/url]
As someone working in a bank call center, I’m terrified by how easy this is getting. We started testing Sensity recently, but it struggles with audio clips under 3 seconds https://fun-wiki.win/index.php/Deepfake_Detector_for_Customer_Service:_What_Should_It_Actually_Flag%3F
Honestly, I really wanted to bring my cat to my student flat, but the £250 pet deposit my landlord requested completely ruined my budget fish tank monthly cost
UK88 được xây dựng theo hướng một nền tảng nội dung có cấu trúc rõ ràng và dễ tiếp cận, giúp người truy cập nhanh chóng xác định khu vực mình quan tâm bbc
mostbet bónuszkód [url=www.mostbet2024.help]mostbet bónuszkód[/url]
SIN88 được xây dựng theo hướng một nền tảng nội dung có cấu trúc rõ ràng và dễ tiếp cận, giúp người truy cập nhanh chóng xác định khu vực mình quan tâm bbc
VIN88 được xây dựng theo hướng một nền tảng nội dung có cấu trúc rõ ràng và dễ tiếp cận, giúp người truy cập nhanh chóng xác định khu vực mình quan tâm bbc
XOILAC được xây dựng theo hướng một nền tảng nội dung có cấu trúc rõ ràng và dễ tiếp cận, giúp người truy cập nhanh chóng xác định khu vực mình quan tâm bbc
This $9 billion figure confirms exactly what I see on the ground. Hybrid setups provide incredible value beyond the live day. I especially love how virtual engagement data helps us tailor our future production schedules for both crowds audience segmentation events
Your advice about observing a class first was useful. We watched a session at kids gymnastics carlsbad in Carlsbad and immediately signed up for kids gymnastics.
I’ve been testing a few different indexing workflows lately. While I definitely rely on the GSC URL Inspection tool for manual pushes, I still run into those stubborn ‘crawled – currently not indexed’ pages more often than I’d like https://golf-wiki.win/index.php/Best_Indexing_Tool_for_Bulk_Third-Party_Backlinks_Where_Refunds_Matter
They relocated switches to accessible heights— residential electrical services phoenix cares about usability. Phoenix team.
It is definitely eye-opening to see how much some of these breeds cost to maintain. If you are looking at getting a French Bulldog, I would strongly recommend securing lifetime insurance cover right from the start dachshund ivdd recovery tips uk
I’ve seen firsthand how quickly a DPN can escalate, so thanks for breaking this down. A lot of directors forget that the 21-day clock starts on the issue date of the notice, not when they finally get around to opening the mail illness incapacity defence dpn
Thanks for the great explanation. More info at escapada rural Segovia .
I travel for business constantly, so the stand-upright test is a major selling point for me. There is nothing worse than a bag that flops over in a crowded airport terminal or during a meeting https://cruzqmfp756.theburnward.com/what-briefcase-details-signal-it-s-worth-repairing-not-replacing
This was a wonderful guide. Check out abogado laboral Vigo for more.
My golden retriever is turning eight soon, so I am starting to look at renewal quotes. I have been with Petplan for years and really value their 24/7 video vet service, but the prices are climbing quite a bit https://privatebin.net/?d14fbadd5376c73d#GdaeeNTMuFvPczWFypraHVG8MmMZXgeP8fYkHjDv4haU
As a freelance journalist, I find this tech really impressive. I started using Pindrop to verify audio clips, and it’s a game changer that it can detect fakes in under three seconds how deepfake detectors work
Honestly, the upfront costs are the biggest hurdle. My landlord asked for a £250 pet deposit on top of the usual rent, and that wiped out my savings for the term. It’s tough balancing those costs while trying to study The original source
The brand new taste of whipped cream the usage of these chargers is unbeatable—thanks, http://home4dsi.com/chat/redirect.php?url=https://www.rankbookmarkings.win/at-nangs-delivery-we-take-into-account-the-magnitude-of-high-quality !
As an event lead, I see this shift every day. We capture so much more valuable data now compared to strictly in-person setups https://www.mapleprimes.com/users/logan-fox84
Photo updates reduce owner anxiety; examples and booking on experienced dog walker .
It is true that breeds like French Bulldogs are pricey upfront, but the recurring medical costs really add up. My biggest piece of advice for new owners is to sort out pet insurance as early as possible Visit this link
I’ve been testing various indexing methods lately, and while hitting an 89% success rate sounds great on paper, it’s not always a silver bullet. Even with these tools, I still run into the classic ‘crawled – currently not indexed’ status in GSC constantly indexceptional refund policy
שירות לקוחות מהיר וסבלני – חוויה חיובית בזכות חיפוי מבנים באלומיניום קבלן .
For leash-biting habits, a patient pro helps; ours is from reliable dog walker Chandler AZ .
My renewal is coming up soon for my eight-year-old spaniel and I have been looking at the options. I noticed Tesco Bank offers those handy Clubcard savings which could really help with the cost of cover https://solo.to/haley_stewart1
This is a timely reminder. I’ve seen too many directors get caught out by that 21-day clock, especially when they aren’t monitoring their ASIC registered address closely enough https://www.mapleprimes.com/users/edwardsmith93
As someone who lives in airport lounges, the stand-upright test is a major selling point for me. I’m tired of bags flopping over and spilling files everywhere during boardings. It’s a solid investment if it truly keeps its shape over time Tuscany leather briefcase
Having a cat in my second year was great, but it was definitely pricey. Finding student housing that actually allows pets was the hardest part. I ended up paying a £250 pet deposit which really ate into my budget for the month https://www.inkitt.com/rogerlopez06
I work at a bank call center and we have been struggling to identify synthetic voices during quick verification calls https://www.animenewsnetwork.com/bbs/phpBB2/profile.php?mode=viewprofile&u=1182563
мостбет история ставок [url=https://mostbet45631.help]https://mostbet45631.help[/url]
This $9 billion projection really hits home. We see massive potential in repurposing live session footage into snackable micro-content after the event ends. It keeps the audience engaged long after they log off Great site
мелбет фрибет [url=https://melbet15928.help/]https://melbet15928.help/[/url]
I’ve been struggling lately with that pesky ‘crawled – currently not indexed’ status in GSC. I’ve experimented with Rapid Indexer VIP for a few projects, and it does seem to speed things up, but it’s definitely not a magic wand wordpress indexing plugin
It is true that breeds like the French Bulldog can be quite pricey to maintain due to their specific health needs. I always recommend getting lifetime insurance cover as soon as you bring them home because those vet bills add up quickly Additional reading
The burst fade gallery gave me ideas; my cut from barbershop haircut matched perfectly.
If your pet gets cold easily, pet groomers fayetteville Fayetteville, NC offers warm towels and shorter dry times.
Dealing with insurance adjusters on a diminished value claim has been frustrating. I’m considering talking to a California attorney and saw that diminished value claim attorney California specializes in this area.
I’ve been looking at ManyPets for my two-year-old spaniel since our renewal is coming up in March. That 24/7 video vet feature sounds really handy for peace of mind, especially during those late-night panics Additional hints
I believe having a backyard deck is important for amusing visitors! It produces the best atmosphere for barbecues and events deck builders