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
}
мелбет спорт бонус [url=https://melbet15928.help]мелбет спорт бонус[/url]
The $9 billion projection really resonates with my experience on the ground. We definitely see more clients investing in hybrid formats now. One massive benefit we track is the data captured from virtual attendees https://qnaln.stick.ws/
As a recent grad, I totally get this struggle. Trying to balance vet bills with student loans was nearly impossible. Even finding a place that allowed a cat meant paying an extra £200 pet deposit on top of the regular rent, which just wiped out my savings monthly cost of gold fish
As a frequent flyer, the stand-upright test is usually the first thing I look for when choosing a new bag. Nothing is worse than my briefcase tipping over in an airport lounge or meeting room. This model seems to solve that annoying problem quite well why solid brass hardware matters
As a journalist, I’m constantly worried about verifying clips before publishing. I recently started testing Pindrop to see if it can handle the short snippets I get sent. It’s tough when I only have access to clips under three seconds for analysis deepfake audio scanner for mac
It is true that breeds like the French Bulldog can be quite costly to maintain long-term. If you are considering one, I definitely recommend getting comprehensive lifetime insurance as soon as you bring them home https://elise_moore1.raindrop.page/bookmarks-70723311
I’ve been experimenting with these methods lately, and while the GSC URL Inspection tool is my go-to for checking status, it can be frustrating https://lilysbestblog.theburnward.com/how-to-actually-get-your-backlinks-indexed-and-why-most-seos-fail
As someone who has been through this, the 21-day clock is definitely the most stressful part of receiving a DPN. Once that notice hits your ASIC-registered address, there is no time to waste how to calculate 21 day period dpn
I have been looking into cover for my 8-year-old spaniel since my renewal is coming up in a couple of months. The Tesco Bank Clubcard savings feature is quite tempting for us More help
Honestly, bringing my cat to uni was a massive financial hurdle. The £250 pet deposit my landlord charged nearly wiped out my food budget for the month. It was worth it for the company, but I definitely struggled to make ends meet at times https:///Thinking-of-a-pet-in-your-student-house-It-is-a-big-move-With-food-and-an-35c06a86410680d2a298c724ee5b0c8f
As someone who spends more time in airport lounges than my own office, I really appreciate the emphasis on the stand-upright test. It is a nightmare when my bag flops over in the terminal. That build quality seems perfect for my travel schedule 5 year warranty briefcase
Вызов капельницы от похмелья с контролем врача в Самаре рекомендуется, когда симптомы похмелья становятся особенно тяжелыми и мешают нормальной жизнедеятельности. Несмотря на то, что многие пытаются справиться с похмельем с помощью домашних методов, такие как прием жидкости или таблеток, они не всегда оказываются достаточно эффективными. В случае сильных симптомов похмелья, капельница с врачебным контролем — это более безопасное и быстрое решение, при этом возможен вывод в стационаре, анонимное лечение и консультации по вопросам наркомании с учетом актуальной цены услуг.
Углубиться в тему – [url=https://kapelnicza-ot-pokhmelya-samara-13.ru/]капельница от похмелья на дом самара[/url]
If you want flexible weekend appointments in Houston, check carpet cleaning houston Houston, TX .
888starz official [url=www.888starz-uz3.org/]www.888starz-uz3.org/[/url] .
http://pt-internetservice.de/
Das Projekt Pt Internetservice ist ein erfahrene Beratung praesent im den nationalen Rahmen Deutschlands, das bereitstellt massgeschneiderte Loesungen fuer alle die Effizienz schaetzen, priorisierend auf Vertrauen und Transparenz. Besuchen Sie die Website ueber den Link.
I’ve been testing these tools lately, and honestly, nothing beats the GSC URL Inspection for diagnostics https://www.protopage.com/nora_dixon22#Bookmarks
Service area businesses can still win near me queries; our setup is on small business SEO company NYC .
This was beautifully organized. Discover more at casas rurales para familias Segovia .
My daughter was afraid of tumbling until her coach at gymnastics encino in Carlsbad broke everything down into simple steps in kids gymnastics.
This was highly educational. More at asesoría jurídica Vigo .
mostbet ставки на киберспорт Кыргызстан [url=http://mostbet45631.help]http://mostbet45631.help[/url]
mostbet kártyajátékok [url=http://mostbet2024.help/]mostbet kártyajátékok[/url]
Excellent breakdown on flooring types. For a trusted Charlotte contractor, look at local flooring company .
There’s nothing rather like taking pleasure in a summertime evening on a well-designed yard deck deck builders
Your coverage of condensate drains helped me spot a clog. Chicago, IL water heater chicago cleared it in Chicago.
мелбет login [url=https://melbet15928.help/]мелбет login[/url]
Your puppy intro guide is great. We do short “happy visits” just for treats and touching paws/ears so pups build positive associations. What age do you like to start? Reno NV pet salons
Thanks for the valuable insights. More at divorce mediators .
פתרו לי כאב ראש גדול – תודה: בניית אתר תדמית
Comfortable place for sharing a meal and enjoying latin cuisine with friends or family. latin food Spring TX
подробнее [url=https://elliottconnie.com]kraken onion[/url]
star 888 [url=http://www.888starz-uz1.org]star 888[/url] .
استار 888 [url=https://888starz-egypt9.com]https://888starz-egypt9.com/[/url]
Reliable backups are essential; I list my coverage network on dog walkers in Durham .
This post clarified panel upgrades; we booked a consultation through licensed electrician services Garland .
Наркологическая клиника в Хабаровске решает несколько ключевых клинических задач, начиная от диагностики и заканчивая длительным наблюдением. В клинике «Северный Путь» акцент делается на точную оценку состояния пациента при поступлении, что позволяет корректно определить тактику терапии и прогноз восстановления.
Получить дополнительные сведения – [url=https://narkologicheskaya-klinika-khabarovsk0.ru/]вывод наркологическая клиника[/url]
мостбет вход на сайт [url=mostbet45631.help]mostbet45631.help[/url]
мелбет правила [url=https://www.melbet15928.help]https://www.melbet15928.help[/url]
mostbet élő események [url=www.mostbet2024.help]www.mostbet2024.help[/url]
mostbet befizetési problémák [url=https://www.mostbet2024.help]mostbet befizetési problémák[/url]
maorou_k8m maorou_k8m porn
For generator interlock kits, Phoenix, AZ wiring installation phoenix gave us peace of mind. Phoenix homeowners, check them out.
К основным показаниям относятся:
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-v-staczionare-nizhnij-novgorod-2.ru/]вывод из запоя в стационаре нижний новгород[/url]
The hot towel shave breakdown was spot-on; I found a local pro via barber near me .
mostbet cashback feltételek [url=https://www.mostbet2024.help]https://www.mostbet2024.help[/url]
888 start [url=http://www.888starz-uz3.org]888 start[/url] .
Local moving companies in Jersey City really understand apartment moves and tight building spaces. Local movers Jersey City
Well done! Find more at pet friendly casas rurales Segovia .
Love seeing regional remodels! We just done a small tub replace in San Diego and found that making plans round lead instances for tile and custom glass made a immense distinction. Also, money nearby code standards for GFCI retailers and anti-scald valves go to my blog
Love the level about sunscreen texture on peeling skin—gel-cream codecs in fact decrease roll-off all through facial slough. I gathered product textures that layer smartly over flakes and don’t tablet; info here: pop over to these guys .