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://autisminfo.ru/news/7233-kogda-roditel-zavisim-kak-zashhitit-rebyonka-s-autizmom-ot-posledstvij-semejnogo-alkogolizma]вызвать капельницу на дом[/url]
I think the move toward simpler payments is a real relief. I’ve always found it tedious to type out long card numbers on my small phone screen, especially when I’m on the go https://hectoroypj356.huicopper.com/the-one-click-revolution-how-instant-payments-changed-everything
Living here by the shore, I have definitely noticed more people playing on their phones lately. I was waiting for my friends at the pier last week and saw a guy spinning slots while watching the sunset More helpful hints
I really feel this trend. I find myself scrolling through short videos whenever I am waiting in line for my morning coffee. It is so convenient to catch up on news in just a minute https://charliekzxa221.huicopper.com/why-convenience-matters-more-than-ever-in-apps
Honestly, I think these digital hangouts are a double-edged sword. Between my chaotic schedule and friends living across three different time zones, hopping into a call for even just 10 minutes is often the only way we stay connected anymore https://verawilson95.livejournal.com/profile/
Shoutout for awesome provider on a sloped backyard in Bellevue’s Lake Hills domain—real stepping, reliable gate alignment, and transparent verbal exchange on timelines additional hints
Текст посвящён распространённым мифам о зависимости и их развенчанию. Мы предоставим научно обоснованную информацию и дадим рекомендации по выбору эффективного способа борьбы с зависимым поведением.
Заходи — там интересно – [url=https://divoch.ru/5-opasnyh-zabluzhdeniy-o-domashnem-lechenii-pohmelya-i-bezopasnye-sposoby-vyhoda-iz-zapoya/]снятие похмелья капельницей[/url]
В этом исследовании рассмотрены методы лечения зависимостей и их эффективность. Мы проанализируем различные подходы, используемые в реабилитационных центрах, и представим данные о результативности программ. Читатели получат надежные и научно обоснованные сведения о данной проблеме.
Что ещё нужно знать? – [url=https://lavrus.org/preimushhestva-vyzova-narkologa-na-dom-dlya-lecheniya-i-podderzhki-pri-zavisimosti.html]clinica plus[/url]
I’ve been looking into options for a loved one, and the clear descriptions on Depression Treatment Newport Beach helped me understand how intensive depression treatment in Newport Beach can support them during a difficult time.
Hi i am kavin, its my first time to commenting anyplace, when i read
this article i thought i could also create comment due to this sensible piece
of writing.
Great article! I’ve been noticing how much smoother deposits are lately. It’s wild how tokenization has really changed the game for security, making it feel much safer to play https://wiki-room.win/index.php/Why_Does_4G_Latency_Mess_Up_Payment_Verification%3F_A_Deep_Dive_for_Mobile_Players
I never thought about endurance racing like an RNG system before, but the comparison makes total sense. Strategy teams basically calculate odds every lap while managing tire drop-off https://juliussinterestinginsight.image-perth.org/deconstructing-the-grid-a-data-analyst-s-guide-to-racing-sports-cars
I totally agree that having on-demand shows makes my long train commute and post-gym cooldowns so much more relaxing. It is a game changer for sure relaxation routines for busy schedules
It is honestly a game-changer to finally have a decent connection out here. Before this, we had to make a forty-minute drive just to find a movie theater or arcade https://archerbqhu039.cavandoragh.org/entertainment-beyond-location-how-rural-connectivity-changed-the-rules
I think Julian Alvarez needs to move on if he wants to be the main man. He is a fantastic talent, but he will always be a secondary option behind Haaland at City. At his age, he deserves to lead the line for a top club https://zacharyfisher02.livejournal.com/profile/
Solid methods! In North Phoenix, a 4,000–4,500 PSI mix with fiber or rebar can virtually aid opposed to cracking from temperature swings. I additionally propose a pale broom conclude for traction for the period of summer time grime storms Homepage
Great read! If any contractors here are looking for detailed Orange County utility locating services, I recommend checking out Orange County Utility Locating before you break ground.
Great post on streamlining the conversion funnel. I’ve noticed that players are way more likely to convert if they can filter games by volatility right on the landing page https://johnnywrbo401.wpsuo.com/rtp-and-volatility-do-they-actually-drive-slot-search-behavior
Honestly, I really appreciate any push toward simpler payment methods. Trying to type out my long card number on a tiny phone screen is always a hassle, so carrier billing definitely sounds like a nice upgrade for convenience Get more information
Living here on the coast, it’s wild how much mobile gaming has changed things. I often pull up a few hands while waiting for friends at the boardwalk bar https://simonvsaz605.almoheet-travel.com/the-pocket-sized-casino-how-gulf-coast-leisure-is-moving-from-boardwalks-to-bandwidth
I find myself scrolling through these quick reads whenever I’m waiting in line for my morning coffee. It’s honestly such a relief to get the gist of a story without needing a half-hour block of time. I really appreciate the convenience of it all https://www.magcloud.com/user/william-lopez06
В этой статье рассматриваются актуальные вопросы, связанные с развитием медицинской науки и её внедрением в повседневную практику. Особое внимание уделено вопросам профилактики, ранней диагностики и использованию технологий для улучшения здоровья человека.
Слушай внимательно — тут важно – [url=https://lolifruit.ru/poleznaya-informaciya/trevozhnye-signaly-kogda-blizkomu-trebuetsya-srochnaya-narkologicheskaya-pomoshh-pri-otravlenii-alkogolem/]нарколога домой[/url]
Appreciate the thorough analysis. For more, visit casa de aldea Arzúa .
Eco-conscious note: recycling the catalytic converter and metals keeps junk out of landfills. cash offer for my junk car estero explained their recycling process clearly.
Spot on with this write-up, I absolutely believe this
site needs a lot more attention. I’ll probably be back again to read through more, thanks for
the advice!
Είναι σημαντικό να εξηγούμε στους χρήστες πώς να χρησιμοποιούν σωστά μια χημική τουαλέτα για να μένει καθαρή. Ένα ενημερωτικό φυλλάδιο σαν αυτά που έχει το τουαλέτες festival βοηθά πολύ.
A well-structured approach to understanding underground utility issues; I learned a lot from this post, thank you again! Fresno underground utility locating
Pro tip: have your title ready— scrap car buyers Fort Myers FL guided me through the Florida DMV steps when I scrapped my car in Fort Myers.
I think online platforms are a bit of a double-edged sword. With my chaotic schedule and friends spread across several time zones, being able to hop into a voice channel for just 10 minutes is a total lifesaver https://www.instapaper.com/read/2020278113
I really appreciate the breakdown on payment gateways! It’s wild how much smoother things run when the tech is integrated properly. I’ve personally had way better experiences since platforms started optimizing their checkout flows View website
Great data on preserving masonry! In Santa Ana we see a great number of cinder block walls crack from soil move and sprinklers soaking the bottom. I had fulfillment repointing and sealing, but greater stair-step cracks obligatory seasoned aid his explanation
Businesses upgrading from legacy phone systems in California should coordinate with cabling providers like Cabling Services Provider California for a smooth transition.
This is a fascinating way to look at racing strategy. I love the comparison between game RNG and endurance racing volatility. Safety car timing really acts like a massive multiplier that ruins the best-laid plans Hop over to this website
Growing up in a tiny town, we had to drive an hour just to see a movie. Now that my kids can hop into a lobby with friends, it makes those long evenings after farm work feel a lot less isolating https://escatter11.fullerton.edu/nfs/show_user.php?userid=9809921
The point about optimizing internal linking pathways really resonated with me. I often see sites just dumping links at the bottom, but guiding the reader through the journey seems like a much smarter way to improve conversions google search central gaming advice
I totally agree that on-demand entertainment makes my daily train commute and post-gym cooldowns so much more relaxing. I even catch up on shows during my lunch break now habit formation through smartphone apps
Living right on the boardwalk, I see people on their phones everywhere now. It’s perfect for killing time on a rainy afternoon when the beach is off-limits. While I love the convenience, I still worry about security with these apps website
I honestly think Julian Alvarez needs to move again if he does not become the main man at Atletico by 2026. He is in his prime and clearly talented enough to lead the line for a top club. Sitting on the bench feels like a waste of his potential Xabi Alonso exit Madrid
For Goodyear owners near PebbleCreek or Estrella Mountain Ranch, evaluate slip-resistant tile (DCOF-rated) and occasional-upkeep quartz for vanities. Also ask about lead instances on specified-order fixtures a fantastic read
Finding Bee Spotted was the turning point for our landscaping company in Billericay. We had no online presence to speak of and within six months we were on page one for our most important keywords. The phone has not stopped since.
SEO Agency Basildon
I definitely agree that the payment process needs to be smoother. Personally, I hate having to pull out my wallet to type in long card numbers while I am on my phone. It is just too much of a hassle https://atavi.com/share/xw8gaczwp5qd
I find myself scrolling through these short articles every single morning while waiting in line for my coffee. It is honestly such a huge help for my busy schedule http://www.video-bookmark.com/user/brianhayes85
В этой статье рассматривается комплексный подход к избавлению от зависимости. Читатель узнает, как сочетание физического, психологического и духовного восстановления помогает достичь стойкого выздоровления.
Ознакомиться с полной информацией – [url=https://happyner.com/alkogol-vs-dofamin-kak-obmanut-mozg-i-nayti-schaste-bez-bokala/]нарколог на дом вывод из запоя на дому[/url]
Hmm it seems like your site ate my first comment (it was extremely long)
so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog.
I as well am an aspiring blog blogger but I’m still new to everything.
Do you have any tips for first-time blog writers? I’d definitely appreciate it.
pronostici e Scommesse Italia vincenti
I’ve always been a bit nervous about security with online sites, but this breakdown on tokenisation makes a lot of sense. It’s good to know my actual card details aren’t being stored everywhere optimizing casino payment gateways
Thanks for the thorough article. Find more at alopecia femenina Albacete .
Thanks for the insightful write-up. More like this at mejor clínica capilar Jaén .
Moving a warehouse office in Cincinnati? Check forklift access, pallet counts, and mezzanine clearances. I picked up a pre-move survey sheet from Cheap movers Cincinnati .
promo Virtual wedden Tips 2026