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’m really concerned about work injuries and how they can affect both employees and employers. It’s crucial to have safety protocols in place! Workers Compensation
Having external audits conducted regularly ensures compliance remains intact while identifying areas needing improvement thus enhancing overall operations success.-#WorkInjury#ExternalAudits### anykeyword ## Work Injury
Терапевтический алгоритм в стационаре не сводится к единой разовой манипуляции. Это последовательная система диагностики, стабилизации, медикаментозной поддержки и подготовки к амбулаторному этапу, выстроенная с учетом современных стандартов наркологии 2026 года. При поступлении врач проводит детальный неврологический и соматический осмотр, собирает развернутый анамнез, оценивает когнитивные функции и при необходимости назначает лабораторные исследования. На основе полученных данных формируется индивидуальный протокол, учитывающий возраст, длительность интоксикации, наличие хронических заболеваний и переносимость лекарственных компонентов. Мы отказываемся от универсальных схем в пользу точного дозирования, что ускоряет восстановление метаболических функций и снижает вероятность побочных реакций.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-v-staczionare-nizhnij-novgorod-10.ru/]вывод из запоя в стационаре анонимно нижний новгород[/url]
Have used Harland Windows and Siding throughout three different properties over two decades. The pleasant and professionalism have been regular each time. They are the simplest window agency I name. Window installation Raleigh
Strong argument for topical depth. Our Phoenix SEO cluster approach is detailed at Phoenix SEO .
We wish to dominate Phoenix “emergency situation” questions. Testing on-page seriousness signals with SEO Phoenix .
Post útil. Si buscáis técnicos fiables para apertura de puertas Barcelona, mirad cerrajero 24 horas .
I always schedule a fall wellness visit to prevent stiffness before winter hits. Tacoma car accident chiropractor
Hydroseeding grows directly into your soil, unlike sod, which helps promote deeper, healthier roots. Hydroseeding near me
В данной статье мы акцентируем внимание на важности поддержки в процессе выздоровления. Мы обсудим, как друзья, семья и профессионалы могут помочь тем, кто сталкивается с зависимостями. Читатели получат практические советы, как поддерживать близких на пути к новой жизни.
Получить дополнительную информацию – [url=https://mastersolution.ru/2026/05/01/pyat-shagov-podderzhki-kak-pomoch-blizkomu-spravitsya-s-alkogolnym-krizisom/]выведение из запоя на дому в екатеринбурге[/url]
This is quite enlightening. Check out Divramis digital agency for more.
I really appreciate this perspective. After chasing every new trend in my fifties, I finally realized that simple consistency works best. Your point about moving away from quick fixes rings so true https://www.mediafire.com/file/lw96qe41bp92tgr/pdf-27540-8163.pdf/file
Oh my goodness! Amazing article dude! Thank you, However I am going through troubles with your RSS.
I don’t know why I cannot subscribe to it.
Is there anybody else having the same RSS issues?
Anybody who knows the answer can you kindly respond?
Thanks!!
I really resonate with this. It’s so frustrating when people tell me I look fine when they have no idea what I’m feeling inside. Yesterday I had to cancel dinner plans at the last minute because I just didn’t have the energy to leave the house https://www.mediafire.com/file/scht6ifcu1b8h69/pdf-28709-37564.pdf/file
It’s really encouraging to see the club taking such a cautious approach with the staged reintegration of our returning players https://www.scribd.com/document/1035875097/The-Anatomy-of-a-Collapse-Liverpool-s-2020-21-Centre-Back-Crisis-150698
Non-economic damages are real. Auto Accident explains them and lawyers know how to present them persuasively.
1win mobil kazino [url=http://1win49027.help/]http://1win49027.help/[/url]
Useful guide on review speed. Anybody usage Phoenix SEO to construct a Phoenix review-generation workflow?
For multi-location Phoenix brand names, canonicalizing city pages is essential– best practices at SEO Phoenix .
I really appreciate this perspective. In my fifties, I am finally done chasing the latest wellness fads that promise overnight results. They rarely work long-term. Instead, I focus on the basics that actually make a difference https://romeo-wiki.win/index.php/What_Should_I_Focus_on_First:_Sleep,_Food,_or_Exercise%3F
Reading this really highlights the grit required to play in the Scottish leagues. It is easy to overlook the physical cost when watching from the stands why does my body ache after football
Thanks for the insightful write-up. More like this at tint installers greenville .
pariuri pe cartonase melbet [url=www.melbet63149.help]www.melbet63149.help[/url]
It is wild to see Cristiano still performing at this level. Whether or not he makes the 2026 World Cup, his drive is incredible https://www.4shared.com/office/0MvWAmPBjq/pdf-31141-40432.html
Valuable information! Discover more at neck pain relief .
Thank you so much for sharing your story. I know exactly how frustrating it is when people say, “but you look fine,” even when I’m struggling just to stand up. It feels like such an uphill battle to be understood https://mike-wiki.win/index.php/The_Golden_Hour_Trap:_Why_We_Overcommit_When_We_Feel_%22Okay%22
Really interesting read on the recovery protocols. It’s reassuring to see how careful the medical staff is with the staged reintegration process, especially given how tight our schedule has been lately typical recovery time for football injuries
I learned this the hard way with private physio when the follow-up costs really added up. Now, I always ask for full upfront pricing before I commit to any treatment plan. It definitely saves me from stressful surprises https://www.4shared.com/office/rWeQpO3yjq/pdf-25944-58057.html
I really struggled with neck tension during long listening sessions until I finally moved my speakers up to ear-level. It made a world of difference. Now I also make sure to stand up and stretch between album sides to reset my posture more info
I really appreciate this perspective. In my fifties, I finally stopped chasing every new trend and realized that simple consistency wins every time consistent routines health
It is really eye-opening to read about the physical reality for these players. Dealing with that level of Monday morning stiffness after a ninety-minute battle is tough enough, let alone doing it while balancing a day job https://romeo-wiki.win/index.php/Is_Stretching_Enough_for_Football_Recovery,_or_Are_You_Wasting_Your_Time%3F
http://izigraph.fr/
La societe Izigraph se positionne comme une agence specialisee orientee vers le public en France, qui propose des solutions sur mesure aux entreprises et particuliers, avec un accent sur l’attention personnalisee. Visitez le site sur le site officiel.
It is honestly impressive to see Ronaldo still pushing this hard for the title with Al Nassr. People doubted him, but he keeps proving everyone wrong https://sticky-wiki.win/index.php/Is_Al_Nassr_Actually_Going_to_Win_the_Saudi_Pro_League_This_Season%3F
mostbet tennis stavka [url=mostbet38506.help]mostbet38506.help[/url]
I really resonate with what you wrote about invisible pain. That comment about looking fine always hits hard when I am actually struggling to get through the afternoon https://rentry.co/rqs85zk6
melbet délai vérification [url=https://www.melbet04739.help]https://www.melbet04739.help[/url]
мелбет пополнить с мбанк [url=www.melbet73624.help]www.melbet73624.help[/url]
vavada strategie lucky jet [url=https://vavada2001.help]https://vavada2001.help[/url]
It’s great to see the club taking such a cautious approach with recent injury setbacks https://elliotsimpressivedigests.huicopper.com/the-anatomy-of-the-crisis-why-liverpool-s-position-specific-injuries-hurt-more
I really appreciated this post. I used to deal with constant neck tension during long listening sessions. Raising my speakers to ear level and finally switching to a better chair helped a lot. Now I make sure to get up and stretch between album sides how to sit while listening
The duct design tips helped our remodel. We matched with a pro at hvac repair service near me .
I once got stung by hidden admin fees at a private GP clinic, which was a huge shock. Now, I always ask for total upfront pricing before booking any appointment. It saves so much stress in the long run private healthcare costs UK
I love what you guys are up too. This type of clever work and coverage!
Keep up the awesome works guys I’ve incorporated you guys to my personal
blogroll.
What I liked maximum approximately Harland Windows and Siding become the straightforward information. They advised me which windows considered necessary alternative and which had been still fantastic. No upselling. Refreshing. Window installation Raleigh
Combining massage therapy and chiropractic care has helped manage my arthritis pain. Tacoma injury chiropractor
Hydroseeding from ORCA gave us a lush, safe lawn where our kids can play—without harsh chemicals. Hydroseeding services
It’s honestly brutal how much these guys put their bodies through every week. You can see how heavy those mid-winter pitches get, but the real story is that Monday morning stiffness players face while heading back to their day jobs compression gear for football players
I love this perspective. In my fifties, I have finally realized that chasing the next viral wellness trend just wears me out. Returning to the basics feels so much more sustainable walking vs running for older adults
It is honestly impressive to see Ronaldo still pushing this hard for the title with Al-Nassr. Even at 41, his hunger for goals never seems to fade. Watching him compete like this makes me wonder if he really will hold out for the 2026 World Cup https://sophiasexcellentchat.wpsuo.com/al-nassr-vs-al-ahli-why-this-saudi-pro-league-night-matters-in-madrid
I really appreciate you sharing this perspective. It hits so close to home. The worst part is always the “but you look fine” comment from people who have no idea how much effort it takes just to show up improving sleep quality with fibro