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
}
Your agrivoltaics mention was fascinating. solar installation stockton Stockton, CA designed higher racking for pasture use.
I honestly find these online hangouts a bit draining, even though they’re convenient. Between my crazy work schedule and friends scattered across different time zones, just hopping on a call for 10 minutes feels more like a task than a genuine catch-up Browse this site
Your emphasis on protecting workers resonates with us. We view Orange County utility locating by Orange County Utility Locating as an essential safety measure, not just a box to check before excavation.
Product preparation are still volatile. A GC I employed via general contractors denver secured key items early and supplied alternates, which kept our LoHi renovate relocating.
Nicely done! Discover more at reservar pensión Arzúa .
I appreciated this post. Check out dónde dormir en Arzúa for more.
I totally agree that having on-demand shows during my long bus commute or right after a gym session is a game-changer for downtime best on-demand relaxation apps
I think Julian Alvarez might need a change by 2026. He works hard, but he really needs a system built around him to reach his peak. Staying at Atletico might not give him the minutes he wants as a true number nine https://files.fm/u/533zs8x8z4
I think the move toward simpler payment methods is long overdue. I really hate trying to type out my full card number on a tiny phone screen, especially when I’m out and about Visit this website
I appreciated this article. For more, visit cuidado en casa para mayores .
I find myself scrolling through these short articles while waiting in line for my morning coffee. Honestly, it is so convenient to get a quick idea or a bit of news when I only have a couple of minutes to spare engaging users with micro content
I think moving to online hangouts is a double-edged sword. Between my chaotic schedule and friends across different time zones, hopping on a call for just 10 minutes to say hi is a lifesaver. Still, it lacks the warmth of being in the same room https://record-wiki.win/index.php/The_Flickering_Cursor:_How_Real-Time_Chat_is_Rewriting_Entertainment
Перейти на сайт [url=http://vodkabet-vodka.com/]водкабет[/url]
Incentives change often— solar power installation near me Sacramento, CA tracks federal and state solar credits to lower upfront cost.
For industrial facilities in California, rugged cabling solutions designed by Cabling Services Provider California can handle harsh environments.
I really enjoyed this breakdown of probability in racing. The comparison to RNG systems makes perfect sense. I often think about how one poorly timed safety car ruins a team’s race strategy regardless of their pace https://www.scribd.com/document/1051644523/Deciphering-the-Chaos-Strategy-Probability-and-the-2024-Rolex-24-at-Daytona-210308
Living out here in the country, the nearest movie theater is over an hour drive away, so gaming has been such a game-changer for me https://www.4shared.com/office/m_ICi35fjq/pdf-18621-16452.html
I totally agree that having on-demand shows makes my long train commute feel so much shorter. It is definitely a lifesaver when I am winding down post-gym. That said, I do worry that I am trading real downtime for mindless scrolling on-demand relaxation for travelers
Julian Alvarez moved to Atletico recently, but if he struggles to find his rhythm under Simeone by 2026, a move to the Premier League makes sense. He needs a system that prioritizes high pressing to showcase his work rate https://weekly-wiki.win/index.php/Why_Would_Manchester_City_Want_Enzo_Fernandez%3F_An_Analytical_Deep_Dive
I found your point about internal linking pathways really interesting. It makes sense that guiding players from informational content directly into specific game lobbies would improve conversion rates significantly filters sorting game lobby
Great insights! Find more at เว็บหวยออนไลน์ที่เชื่อถือได้ .
I am really inspired together with your writing skills as well as with the format in your blog.
Is that this a paid subject or did you customize it yourself?
Either way keep up the excellent high quality writing, it’s uncommon to
peer a nice weblog like this one nowadays..
I agree that payment processes really need to be smoother. Personally, I get nervous typing my full credit card info into a mobile browser, so having options like carrier billing is a total game changer. It makes everything feel much more secure Helpful hints
If you’re looking for compassionate care for depression, consider reaching out to teen therapist orange county !
I love how the desert climate is sunny year-round, but my skin definitely doesn’t— Skincare Services Las Vegas has some helpful resources on sun-focused skincare services in Las Vegas.
I totally get why short-form content is winning. When I am stuck in line waiting for my morning coffee, I find myself scrolling through these quick clips instead of digging into long articles instant feedback loops
Living here by the harbor, I find myself pulling out my phone while waiting for the ferry to pick up my friends. It is definitely a fun way to kill time, but I have to agree that these apps will never replace the energy of a real casino floor https://www.mediafire.com/file/emq4mu01to75gm2/pdf-67568-78118.pdf/file
If your utility needs recloser upgrades, nearby solar power companies flags potential interconnection costs early.
This guide on fixing leaks is helpful, but sometimes the crack is hard to find. For anyone in Irvine CA who needs more advanced leak detection on ponds or fountains, I suggest checking Fountain And Ponds Repair Irvine CA for local repair pros.
Kudos to all the psychologists working hard in Newport Beach! Check out their work at Depression Treatment newport beach .
Народ, подскажите, кто искал насчет последнего обновления этого экшена на Android. Долго искал на нормальную версию с модами. Если по факту, куча ресурсов пихают битые файлы, но этот билд запустился без проблем.
Особенно порадовало, так это полный доступ ко всем фичам. Лично я играю несколько дней — все плавно. Для тех, кто сомневается, в этой версии максимально комфортные условия. Никаких надоедливую рекламу. Это реально, когда нужно наслаждаться геймплеем без донатов.
Если вы тоже хочет актуальные новости или хочет задать вопрос, рекомендую посмотреть здесь: [url=https://ok.ru/rootapk/topic/159146186057100]перейти на сайт[/url]
Там авторы постоянно обновляют рабочие моды, а еще там активное чат. Поверьте, проще сидеть в одном месте, чем постоянно гуглить какой-то фейк.
Лично мне, в текущих реалиях надежнее всего доверять социальными сетями, так как в соцсетях сразу понятно, живой ли проект. Это дает огромную уверенность в том, что ты не скачаешь очередной троян. Так что, советую мониторить эту соцсеть, чтобы быть в курсе. Удачи всем с выбором! Надеюсь, если этот совет кому-то сократит время. Пишите в комментариях, если тоже тестили эту версию, посмотрим, совпадают ли отзывы. Всем хорошего настроения!
I agree that digital spaces are filling the gap, but it feels like a hollow substitute for a real coffee shop meet-up https://gbubemaster.gumroad.com/
İş kurmayı düşünen Diyarbakır bayan girişimcilere yönelik teşvik bilgilerini eskort Diyarbakır hizmeti üzerinde sıkça güncelliyorlar.
Howdy! I know this is kinda off topic but I’d
figured I’d ask. Would you be interested in trading links or maybe
guest writing a blog post or vice-versa? My website goes over a lot
of the same subjects as yours and I think we could greatly benefit from each
other. If you’re interested feel free to send me an e-mail.
I look forward to hearing from you! Awesome blog by the way!
Vacuum excavation has become our preferred method for exposing services ahead of repairs. I’ll be recommending Sacramento Vacuum Excavation to colleagues looking for reliable Sacramento-based crews.
I enjoyed this read. For more, visit trasplante capilar en Albacete .
Appreciate the insightful article. Find more at técnica FUT Jaén .
I really enjoyed this breakdown of probability in endurance racing. The comparison to RNG systems makes so much sense when you look at the chaos of a 24-hour event https://shed-wiki.win/index.php/WEC_After_Imola:_Why_Strategy_is_a_Game_of_Percentages,_Not_Gut_Feelings
I’ve really noticed how much smoother my gaming sessions have been lately. The shift toward tokenization has definitely made me feel a lot more secure whenever I’m depositing funds. It’s a huge relief not to worry about my data constantly e-wallet vs instant bank transfer
I was confused about whether I needed non-trucking liability on top of my main policy Cheap Box Truck Insurance
Real gains in comfort for our staff on the loading line—thanks to these doors: Commercial Garage Door
I work for a civil engineering firm and we’re always looking for dependable utility data. Having a trusted potholing partner in Orange County like Orange County Utility Potholing helps us deliver more accurate designs and fewer change orders.
Your explanation of what happens if someone dies without a will in California was eye‑opening. Intestate succession often doesn’t match what families expect California Estate Planning
It is about time! Living out here means a forty-five minute drive just to see a movie, so gaming has been a lifesaver for my family fast payouts for mobile slots
I totally agree that having on-demand shows during my train commute or while I am cooling down after the gym makes the day feel way more productive. That said, I do worry that I am becoming too reliant on my phone for every spare moment Article source
I think Julian Alvarez needs to move on by 2026 if he wants to lead the line properly. He spent too much time behind Haaland at City, and now he looks lost in that Atletico system Additional hints
I have been a client of Bee Spotted for just over a year and the monthly reports always show progress. Sharon does not let results stagnate SEO Agency Basildon
I found the section on internal linking pathways really insightful. I have noticed that when sites clearly group games by volatility rather than just genre, players tend to click through much faster what does rtp mean slots
Your article captures the persistence and dedication koi retaining calls for. Respect. most expensive koi auctions
Moving from Duluth to the West Coast, I needed flexible delivery spread; Duluth moving companies outlined storage-in-transit options clearly.