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 really appreciate how these new apps prioritize mobile play. The daily bonuses keep me coming back without feeling overwhelmed by complex mechanics. It feels much smoother than the older browser versions I used to struggle with more info
I really appreciate this post. I have been struggling to keep my weekends under control lately, so the idea of setting a fixed monthly fun limit is exactly what I need https://www.scribd.com/document/1051754379/How-to-Keep-Entertainment-from-Turning-into-an-Open-Ended-Expense-186286
This was such a fascinating breakdown of how these games are actually put together. I used to think RTP was the only thing that mattered, but seeing how volatility and UX design play into the experience makes way more sense now understanding online casino games
The salary ranges and variables were helpful context. I saw regional data on advanced aesthetics training .
I see those streaks on Duolingo and badges in fitness apps everywhere now. It makes things fun, but do we really need constant notifications to stay engaged? I think these features often feel a bit manipulative https://files.fm/u/shb4rttas2
It is wild how much these apps have changed my daily routine. I used to hate standing in line at the coffee shop, but now I just use mobile wallet pay. It feels so much faster and makes me wonder how I managed without it before https://www.scribd.com/document/1051753410/Why-Milestone-Rewards-Actually-Work-And-Why-Most-Apps-Fail-Them-233966
Эта публикация обращает внимание на важность профилактики зависимостей. Мы обсудим, как осведомленность и образование могут помочь в предотвращении возникновения зависимости. Читатели смогут ознакомиться с полезными советами и ресурсами, которые способствуют здоровому образу жизни.
Детали по клику – [url=https://cherry-socks.ru/alkogolnyy-krizis-u-blizkogo-kak-deystvovat-pravilno-i-effektivno/]врача капельницу от запоя[/url]
This article really highlights how gaming infiltrates our daily speech. I noticed my coworkers using “GG” at the end of meetings last week, which felt so strange yet completely natural. It shows how quickly these terms shift into mainstream culture online communities gaming
Helpful suggestions! For more, visit alojamiento con cocina compartida Arzúa .
I honestly prefer live dealers over digital slots because there is just more trust involved when you actually see the dealer spin the wheel in real time. It makes the whole experience feel so much more transparent and engaging multiplayer casino tables
The ratio of staff to residents is critical. In a small community, help with daily activities is more proactive instead of reactive. respite care looks like it emphasizes that responsive care.
The reminder to check how often doctors or nurse practitioners visit is very useful. We recommend that question on assisted living .
It is honestly wild how much mobile gaming has blown up lately. I find myself reaching for my phone whenever I am stuck on a long train commute. The fast loading times make it so easy to jump into a round for just a few minutes before my stop gaming on phone during travel
I appreciate how you highlighted staff training as a major difference. Memory care caregivers are usually trained in dementia behaviors, which can be essential. We share similar insights on memory care .
The comparison of dining support was insightful. In memory care, cueing and supervision at meals can be essential. We offer family checklists on this topic on dementia care .
One big advantage of a small senior home is the calmer environment. It’s easier for staff to notice when someone needs help with walking, toileting, or eating. That’s why I’m interested in options like senior care .
Every case is unique, but having a knowledgeable injury lawyer increases your chances of a successful claim. Check out tips at Wasilla car accident lawyer !
I’ve really noticed how mobile-first design shifts my listening habits. The personalization on Spotify is so good that I rarely search for music anymore because the algorithm just knows what I want next Have a peek here
I totally agree that the best ideas often emerge outside of traditional labs. It’s fascinating that 18 Nobel laureates gathered in that setting to discuss such complex research scientific validity of astrological charts
I’m so glad bingo is finally making a comeback! It’s the perfect way for me to wind down at night after the kids are in bed. Honestly, those 1p tickets make it such a low-pressure hobby for a quiet weeknight https://pastelink.net/sc5h47bo
I really enjoy how smooth the mobile experience feels on these newer platforms. The daily bonuses keep me coming back every morning, which adds a nice bit of routine to my coffee time slot bonus rounds
I really enjoyed reading this perspective on managing entertainment spending. Setting a fixed monthly fun limit has been a total game-changer for my bank account. It really helps me stay on track without feeling like I am missing out on life budgeting apps
This was a fascinating breakdown of how these games actually function under the hood. I really appreciate how you explained the balance between volatility and UX https://wiki-net.win/index.php/Why_do_regulated_casinos_talk_so_much_about_player_protection%3F
Appreciate the reminder to register warranties; I used a tracker from solar power installation near me Auburn, CA .
For latest news you have to pay a quick visit world wide web and on world-wide-web I found
this web page as a best site for most recent updates.
I definitely feel the pressure from Duolingo streaks and those shiny badges, but do they actually help us learn or just keep us addicted? It feels like we are just chasing dopamine hits mobile app retention tactics
It is fascinating how much our routines have changed lately. I used to worry about where my dinner was, but now having precise delivery tracking really helps me plan my evening better https://wiki-burner.win/index.php/Platform_Reliability:_Why_Your_App_Is_Bleeding_Customers
Читатели получат представление о том, как современные технологии влияют на развитие медицины. Обсуждаются новые методы лечения, персонализированный подход и роль цифровых решений в повышении качества медицинских услуг.
Получить дополнительную информацию – [url=https://eugrus.pp.ru/novosti/8481-pochemu-vrachebnaya-pomosch-na-domu-pri-alkogolnoy-intoksikatsii-stanovitsya-glavnym-trendom-megapolisov]вывод из запоя самара на дому[/url]
This article really hit home for me. Gaming slang feels like the default language of the internet now. I even saw a coworker drop a GG after we finished a long project presentation last week. It completely changed the vibe of the meeting streaming chat culture
I tried the lime-cilantro rice and it elevated our taco night. Grateful for the clear instructions and will return to latin food spring tx Zera’s Latin Food for seasoning ideas.
I really enjoyed reading your take on live dealer sites. Personally, the biggest factor for me is the trust element Helpful resources
It is honestly wild how much mobile gaming has blown up lately. I find myself constantly jumping into a quick game during my daily train commute. The fast loading times really make it easy to get a round in before I have to get off at my stop https://fernandowehn083.timeforchangecounselling.com/what-does-fast-loading-gameplay-actually-depend-on
в этом разделе [url=https://retrocasinogames.com]retro casino[/url]
I was searching for more structured help than just weekly therapy, and that’s how I ended up finding depression treatment programs in Newport Beach through Depression Treatment Newport Beach .
It’s fascinating how our habits shift when we can jump between screens so easily. I’ve noticed that Spotify does this perfectly with their cross-device sync. It makes transitions between my phone and desktop seamless, which really keeps me engaged how cross-device accessibility works
I am so glad to see online bingo making a comeback. I usually log on for a few 30-ball games to help me wind down at night after the kids are finally asleep. It’s such a nice way to relax casual mobile gaming
I completely agree that the history of space exploration feels more like a collaborative art form than pure engineering. It is fascinating that 18 Nobel laureates contributed their expertise to these foundational projects why astrology is a pseudoscience
This was such a deep dive into the math behind the games. I always find it fascinating how UX design plays a role in keeping people engaged, but I think the regulation piece is the most important how to choose a slot
I really appreciate how these new mobile slots run on my phone. The fast loading times make a huge difference during my commute. I also find the daily bonuses keep me coming back without feeling like a chore digital wallet casino
For medical offices, cleanliness and odor control after drywall repair and painting are non-negotiable. We used a healthcare-focused contractor located through drywall repair denver who understood these needs.
I really appreciated this post. I have been struggling to keep my entertainment spending in check lately. Setting a fixed monthly fun limit is such a game changer for me https://jsbin.com/?html,output
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.
I use apps with streaks and badges all the time, and they definitely keep me coming back https://lukasnpyy234.cavandoragh.org/why-are-best-slot-apps-uk-always-pushing-daily-rewards
HOA approvals can slow things— professional solar panel installation had an installer who handled design guidelines smoothly.
I’ve been looking for orthodontic options in Livingston. Can anyone recommend a good clinic? best clear braces for adults
I completely agree with your take on how these apps have changed our daily routines. Honestly, the real game changer for me is the delivery tracking feature. Being able to see exactly where my dinner is on a map keeps me from constantly checking the door data transparency
I completely agree with your take on live dealer games. Honestly, seeing the real cards being shuffled and dealt in front of me makes such a huge difference when it comes to trust https://riverfbdw130.tearosediner.net/what-does-operational-reliability-actually-mean-for-a-live-casino-player
Anyone know a good pediatric dentist in Plano? I’m comparing options on cosmetic dentistry Plano .
I love how gaming slang infiltrates our daily conversations. I recently saw a coworker drop a “GG” in our project slack after we finished a long sprint, and nobody even blinked. It feels like we all speak this secret language now https://shanestue668.yousher.com/the-code-breakout-why-do-glitches-turn-into-memes-so-quickly
Народ, подскажите, кто искал насчет последнего обновления нашего любимого проекта на Android. Перерыл весь интернет на стабильную версию с модами. Если по факту, многие ресурсов выкладывают битые файлы, но этот билд летает на моем старом телефоне.
Что именно круто, так это разблокированное меню. Я сам играю уже неделю — все плавно. Для тех, кто сомневается, внутри максимально комфортные условия. Забудьте про надоедливую рекламу. Это реально, когда можно прокачиваться до максимума без донатов.
Если вы тоже хочет свежие новости или хочет задать вопрос, рекомендую вот сюда: [url=https://t.me/root_apk_ru/233]профиль в соцсети[/url]
Там ребята постоянно заливают новые патчи, а еще там очень адекватное чат. Реально, лучше сидеть в одном месте, чем постоянно гуглить очередной мусор.
Лично мне, сейчас лучше всего пользоваться социальными сетями, так как там сразу понятно, есть ли отзывы. Такой подход дает спокойствие в том, что ты не скачаешь очередной троян. Так что, советую добавить этот ресурс, чтобы не пропускать. Удачи всем с выбором! Надеюсь, что эта инфа вам поможет. Пишите в комментариях, если тоже пробовали этот мод, будет интересно, как у вас впечатления. Всем хорошего настроения!