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
}
Your explanation of what “aging in place” really means in assisted living is clear. We reference that term often on assisted living .
I really appreciate how The Astro AI Chat lets you input your sun, moon, and rising signs for a more personalized reading. It feels more tailored than other apps I’ve tried career astrology reading
I recently implemented a 60-day pilot for team collaboration using Gmail and Docs, and it drastically improved communication flow. Your point about reducing tool overload really resonates with me https://solo.to/megan.brooks2
In a smaller memory care setting, staff often have time for simple but powerful things—sitting to talk, looking through photo albums. That relational care is what I learned to value from assisted living near me .
Слушайте, кто сейчас в теме? То вообще доступ к аккаунту без причин закрывают, Искал реально долго, перепробовал кучу сомнительных вариантов пока чисто случайно не наткнулся на сервис, который работает стабильно и честно, и предлагает топовые условия как для ординаров, так и для экспрессов. Техподдержка в лайв-чате отвечает сразу по делу,
В общем, если не хотите тратить время на самостоятельные тесты, жмите на источник, чтобы случайно не потерять контакты сайт мостбет [url=https://mostbet-bcr.com.kg]сайт мостбет[/url] Лучше обходить стороной забаненные платформы и выбирать надежные зоны. обязательно перешлите этот пост тому, кто тоже сейчас ищет нормальную контору!
nové české casino online vklad 5 kč google pay
I found it really interesting that The Astro AI Chat uses five info fields to personalize readings—it feels like a nice balance between depth and simplicity. I’ve always been curious about how rising signs influence daily moods https://www.hometalk.com/member/250552087/winifred1832262
NYC private rooms can vary a lot, so it’s helpful to compare style, size, and reservation details. This may help: Bar With Private Room NYC
I loved interpreting this breakdown of the Best BTC Casino alternate options. It’s proper to look greater consideration on provably honest video games and crypto-pleasant settlement approaches why not try these out
I recently tried a 60-day pilot to test AWS integration at my company and saw a big improvement in deployment speed. It was great for identifying what worked before fully committing employee security shortcuts
I found it really interesting that The Astro AI Chat lets you input your sun, moon, and rising signs for a more personalized reading. It feels more tailored than generic horoscopes https://amonr.stick.ws/
This article is a good reminder to take roof leaks seriously. Succasunna residents can also visit Roof Repairs Succasunna NJ for roof repair information.
I appreciated this post. Check out clear health guides for more.
Strong reminder to review do not forget notices. Sudden stalls could be covered via a remember—towing to a dealer should be would becould very well be reimbursed. towing near me
The best small homes feel like extended family, not facilities. That emotional safety can slow the decline in some residents. We got comfortable with this idea after reading elder care .
Personalized bathing schedules, preferred hygiene products, and familiar routines are easier to honor in a small home setting. That kind of individual attention is what drew me to senior living .
Professional, punctual, and honest. Exactly what you want from a plumber in Edmonds. Will was great to work with. – Karen T. Plumber Edmonds WA
Excellent overview. Buyers who take time to evaluate the full offer usually make smarter purchasing decisions. ATV Repair
Seasonal checklist is perfect—especially hose bibb inspections. I used Emergency plumbing Moreno Valley to line up a spring plumbing tune-up in Moreno Valley.
cash out correct score betting strategies (Christal) apps
If you desire, I can generate 5 true, non-spammy blog reviews associated with “Excavation Contractor El Reno OK” which can be beneficial, readable, and riskless to publish. click for more info
For hassle-free San Antonio car shipping, San Antonio car moving companies nailed it: no broker games, solid carrier network, and on-time drop-off.
Clean, professional editing throughout — a good standard for Melbourne sports photography labs. contact us
Good article. For AC coil cleaning and repair in Needham, try contact us .
Your description of the food presentation was excellent. A restaurant that cares about small details usually leaves a lasting impression. restaurant Pittsburgh PA
Your article pairs perfectly with some of the comparison worksheets we offer on senior living . I’ll be linking them together.
Your guidance on evaluating communication from management (emails, calls, updates) is very realistic. We mention that on senior care as well.
Love the point about seasonal alterations. I use ET-situated scheduling and published my month-to-month runtime chart here: irrigation system installation .
For winter moves around GR, lake-effect snow worries me—has anyone used Grand Rapids for safe scheduling and weather updates?
It’s helpful to know that Independent Living can be a good stepping stone for seniors who want to downsize but are not ready for personal care services. I first considered that pathway after reading about it on respite care .
Helpful post! A tip for first-timers: confirm pickup accessibility on narrow hilly roads. Roanoke car transportation services arranged a nearby meeting spot to avoid HOA restrictions.
I really like how The Astro AI Chat asks for your sun, moon, and rising signs when you start. It feels more personalized than just a generic reading chiron meaning in chart
I recently implemented a 60-day pilot using Kubernetes for our app deployment, and it really helped streamline our processes. Your points about scalability and cost savings resonate with my experience Visit this site
I like these practical suggestions for apartment moving. New Orleans moves are easier when handled by people familiar with the area. Office moving companies New Orleans is worth looking into.
We wanted algae-resistant shingles; roofer near me in Millsboro sourced AR-rated chances.
american bookmakers
Also visit my web blog; Score Exact Betting Tips Today
I found the inclusion of the five info fields—sun, moon, rising, houses, and transits—on The Astro AI Chat page really helpful for a more personalized astrology reading. It makes the chatbot feel less generic natal chart AI
The reminder to review emergency evacuation plans is critical. I’ll be sure to ask about this when I tour memory care homes I found through elder care .
Специалисты регулярно помогают при интоксикации, запоях, абстиненции и сложных состояниях зависимости.
Углубиться в тему – http://vyvod-iz-zapoya-v-statsionare-v-gelendzhike2.ru/
Very informative. The full customer experience should absolutely be part of any value comparison. Lawn Mower Repair
I recently led a 60-day pilot integrating Kubernetes into our deployment process, and it really streamlined our scalability! Like you mentioned, the early stages feel complex but the payoff is worth it research tool calls
I’m planning a move next month — this Bethlehem moving company seems like a great fit for my needs! Office moving companies Bethlehem
I found it interesting that The Astro AI Chat asks for details like sun, moon, and rising signs to tailor the conversation. It feels more personalized than generic horoscopes astro AI chat compared to apps
For anyone shipping a vehicle from Corpus Christi to the Midwest, what pickup flexibility did you get? I’m testing a few carriers via Corpus Christi auto transport companies .
I recently tried a 60-day pilot involving Kubernetes to improve our deployment speed, and it really streamlined our processes. It was interesting to see how quickly our team adapted compared to traditional methods gemini in slides tutorial
aj beuka high stakes poker, uk casino sign up and canada
online casino slots, or play real money casino app,
Jarred, poker online australia
Thanks for highlighting this topic. Too many people overlook the importance of support and dependability. Utility Vehicle Dealer
Thank you for sharing such detailed insights on garage door repair in Helensvale QLD 4212. The tips on identifying common issues like spring failures and sensor problems were particularly helpful diagnosing sensor issues
Have you noticed higher rates during Lollapalooza weekend? My quote on Chicago car transportation services spiked a bit then.
Example: “Really appropriate post. I imagine many of laborers underestimate how a whole lot planning goes right into a gentle stream, tremendously on the subject of packing fragile objects and loading order.” look at this site