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 appreciated this post. Check out tratamiento capilar Albacete for more.
I found this very interesting. Check out especialistas en cabello Jaén for more.
If your HOA restricts big trucks, ask about a smaller vehicle transfer. I learned to request this in advance when scheduling through Albany car transportation services .
If your repair bill is more than the car is worth, consider cashing out. I used Mome Metals Recycling in Naples and it was painless.
Diyarbakır bayan moda ve güzellik önerileri arıyorsanız yenişehir escort bayan içindeki yerel tavsiyeler işinizi kolaylaştırır.
Heritage Hill homes need careful door jamb protection—ask if that’s standard. I saw it listed clearly on Grand Rapids moving companies profiles.
The community of Newport Beach is lucky to have such dedicated psychologists like those at Psychologist newport beach .
As a small business in Wickford I was not sure I could afford proper SEO help, but Bee Spotted were very upfront about pricing and there were no nasty surprises. More importantly, it worked. We are now top three on Google for our main service.
SEO Agency Basildon
It’s encouraging that # any Keyword # provides a safe space for discussing mental health challenges openly! Psychologist newport beach
Anyone used a Duluth mover with experience in lab/medical office transitions? I found a few specialized teams via Duluth apartment movers .
I found this very helpful. For additional info, visit vivienda turística cerca de Arzúa .
I’m bookmarking this site for future Latin menus. latin food truck spring tx
What stands out with Newmans is the response time. Called on a Thursday afternoon about a non-emergency leak and they were there within two hours. The repair was done properly, the price was fair, and the technician was polite and clean throughout the job Plumber Norfolk VA
Valuable information! Find more at personal loans .
Thanks for the candid talk on earnings and ethics. I’m researching mentorships via medical esthetics school .
What are the best foods to eat while wearing braces, especially if you’re in Livingston? invisible braces options
I like your advice on scheduling maintenance before peak season. I’ve started booking pond cleaning and repair early each year through Fountain And Ponds Repair Irvine CA here in Irvine CA so my water feature is ready by spring.
This was nicely structured. Discover more at precio injerto capilar Albacete .
Wonderful tips! Find more at técnica FUT Jaén .
I was wondering if you ever considered changing the page layout of your
site? Its very well written; I love what
youve got to say. But maybe you could a little more in the way of content so people could connect with it better.
Youve got an awful lot of text for only having 1 or two pictures.
Maybe you could space it out better?
Recovery should fit your life; 24-hour drug detox personalizes scheduling and modalities.
Net metering changes are confusing— solar panel installation estimate tracked policy updates in my state.
Orchard gap detection and replant planning—workflow at autonomous drone spraying .
If your car won’t pass emissions or won’t start at all, these junk car buyers still want it for parts. I used sell my junk car lehigh acres fl and it was painless.
I’m a renter on Kenyon St NW and need same-day help after my original movers canceled. Can Local movers Columbia Heights handle last-minute moves in Columbia Heights?
Explaining the flexibility in Assisted Living—how services can be added as needs grow—is very helpful. That progressive-care idea was also covered in depth on elderly care , which helped me understand long-term planning.
The simple act of recognizing everyone by name, staff and residents alike, builds a sense of belonging in small homes. For someone with memory loss, that belonging is crucial. This was reinforced in articles on memory care .
The ratio of staff to residents is critical. In a small community, help with daily activities is more proactive instead of reactive. senior care looks like it emphasizes that responsive care.
The staff-resident relationships in small environments can be life-changing for someone with dementia. Familiar, trusted caregivers reduce fear. I realized the importance of this after reading about it on senior care .
Hearing success stories from others who took on their own flooring projects motivates me even more! floor restoration near me
This was highly educational. For more, visit asesores contables Saltillo .
Love that you encourage families not to rush the process. We have a step-by-step timeline on respite care that supports that mindset.
Solid breakdown of LCOE— best solar installers Danville has a calculator that includes O&M and inverter swap.
Your reminder about coordinating retirement accounts, life insurance, and trusts is critical. In California, beneficiary designations can completely change how assets pass. For anyone unsure how to align these pieces, California Estate Planning provides good examples
I like how you covered battery add-ons; solar companies near me reviews shows real-world savings with time-of-use rates.
Fantastic advice concerning historic buildings’ preservation efforts—it’s vital we maintain our architectural heritage while also modernizing where possible!! # # anyKeyWord # # shingle roofing contractors
If you care about warranties, licensed solar installers highlights solar companies with strong 25-year coverage.
I like that you mentioned getting multiple quotes instead of relying on one broker. Different insurers view box truck operations very differently Cheap Box Truck Insurance
поиск инвестора для малого бизнеса организация продажи бизнеса
If you’re feeling lost about next steps after your injury, consider reaching out to a professional—an injury lawyer can provide clarity! Learn how at Wasilla Personal Injury attorney .
If you’re dealing with a rat infestation, it’s crucial to address it quickly to prevent health risks and property damage. Effective rat removal techniques can make a significant difference in maintaining a safe and clean environment Pest removal
Appreciate the thorough insights. For more, visit does Java Burn work real results .
Useful advice! For more, visit alojamientos en el Camino Francés .
Fantastic post! Discover more at หวยออนไลน์ล่าสุด .
Публикация знакомит читателей с различными подходами к реабилитации. От традиционных методов до современных программ — вы узнаете, как выбрать оптимальный путь к выздоровлению и преодолеть препятствия на этом пути.
Давай разберёмся досконально – [url=https://coream.ru/razognat-obmen-veshhestv-realnyj-detoks-posle-prazdnikov-i-bezopasnaya-pomoshh-pri-sboyah]вывод запоев скорая[/url]
The onboarding pathway for a para-medical aesthetics technician was helpful. See examples on advanced aesthetics training .
В этом обзоре представлены различные методы избавления от зависимости, включая терапевтические и психологические подходы. Мы сравниваем их эффективность и предоставляем рекомендации для тех, кто хочет вернуться к трезвой жизни. Читатели смогут найти информацию о реабилитационных центрах и поддерживающих группах.
Подробнее можно узнать тут – [url=https://domashniezaboty.ru/vyvod-iz-zapoya-na-domu-pomoshh-narkologa-etapy-i-lechenie-zavisimosti/]clinica plus[/url]
The kitchen drain had been slow for months and finally backed up completely. Newmans came out same day and hydro-jetted the line clear. The technician explained that grease buildup was the issue and gave me some simple tips to prevent it recurring Plumber Norfolk VA
So glad there are dedicated professionals tackling the issue of depression right here in Newport Beach at ##anyKeyword#. teen therapist orange county
Good reminder to ask about visiting policies and flexible hours. I want to stay involved, and I’ll ask detailed questions at the homes I found through respite care .