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
}
Our HOA is strict, but swim lesson miami shores handled the paperwork and insurance to use our community pool.
After a full day on the track, I often deal with a 5 to 10 lb sweat loss and total body fatigue. CBD has been a game changer for my recovery process lately https://quebeck-wiki.win/index.php/Broad_Spectrum_vs._Full_Spectrum:_Why_Motorsports_Professionals_Need_to_Know_the_Difference
Being a student in Peterborough is a solid choice. The train to London makes a massive difference for weekend trips, even if the city itself feels a bit quiet sometimes student budgeting categories
This is such a fascinating topic to consider while planning for a new baby. While cord banking offers potential for future medical use, the high upfront costs and long-term storage fees can be a bit overwhelming for many families https://pastelink.net/kwuhbkbq
As someone working in healthcare compliance, these headlines definitely keep me up at night. The stat about the OIG generating $4.64 for every dollar spent on oversight really puts the pressure on us to have our documentation perfectly locked down https://mega-wiki.win/index.php/How_Should_Providers_Prepare_if_Congress_Changes_Medicaid_Enforcement_Rules_in_2026%3F
This was such a helpful read. I had a total nightmare with my last office renovation because the final bill spiked due to unexpected variation charges – it was so stressful. I have definitely learned to scrutinize the contract much better now https://blogfreely.net/rothesqlmw/how-should-payment-stages-work-for-a-fit-out-contract
I’ve been using Red Team Mode to pressure-test my marketing strategies before launch, and it’s helped me spot several blind spots I would have otherwise missed. Do you find that it works better for high-level strategy or more tactical campaign planning? Find more information
I definitely notice a difference in my complexion when I don’t get enough rest. If I stay up late scrolling on my phone or have a drink before bed, I wake up with puffy eyes and a fresh breakout by the next day https://www.tumblr.com/forsakendragonmaze/819277043833470976/why-does-my-skin-look-dull-after-staying-up-late
Gibraltar is such a unique stop on any Mediterranean cruise! I visited last summer and loved the Upper Rock Nature Reserve https://andreocln282.lucialpiazzale.com/where-can-i-get-the-best-panoramic-view-in-gibraltar
If your chimney flashing is failing round Millsboro, roofing contractor can update it directly.
Этот информативный текст сочетает в себе темы здоровья и зависимости. Мы обсудим, как хронические заболевания могут усугубить зависимости и наоборот, как зависимость может влиять на общее состояние здоровья. Читатели получат представление о комплексном подходе к лечению как физического, так и психического состояния.
Обратиться к источнику – [url=https://moto72.ru/lecenie-alkogolizma-narkomanii-i-bulimii-v-tveri-klinika-klinika-plus/]tver clinica plus[/url]
After a long track day, I usually drop at least 5 lbs in sweat and my muscles feel totally trashed. I have been curious about trying CBD tinctures for recovery, but I worry about product quality restorative sleep for competitive athletes
Thanks for the tree planting calendar — https://www.google.com/search?kgmid=/g/11rfdm5vxn can handle planting and aftercare in New Albany.
visa betting sites on sports with
bitcoin
If your roof pops and creaks, check ventilation and fasteners. Troubleshooting guide at roofing contractor .
Living in Peterborough really grew on me during my time at the university. It is honestly such a convenient base for trips to London. Taking the train down for a day trip or a job interview is super easy since it is only a 50-minute ride https://ericksimpressivenews.cavandoragh.org/do-restaurants-in-peterborough-actually-give-student-discount-if-you-ask
beste wedden euro 2026
Here is my page … online sportwedden tips
This is a fascinating topic that many expectant parents struggle with. While the potential for future medical use is interesting, it is important to remember that these therapies are still largely in the research phase hematopoietic stem cell transplant side effects
Choosing the right contractor in KL is always a nightmare. I’ve learned the hard way that checking their CIDB registration is non-negotiable-it really saves you from so many headaches later on. Your point about vetting them properly is spot on https://www.demilked.com/author/brian-cruz91/
As a billing lead, this talk about the 2026 Medicaid fraud push honestly keeps me up at night. Seeing the OIG figure of $4.64 recovered for every $1 spent really highlights why audits are getting so much more aggressive https://emilianoakpv703.wpsuo.com/is-hospice-enrollment-being-restricted-because-of-medicaid-fraud-concerns
This was a fantastic read. Check out compañía de cuidadores mayores for more.
I’ve been using Red Team Mode to stress-test my project proposals before showing them to the team, and it’s been really effective at pointing out logical gaps I missed https://www.hometalk.com/member/248724511/daniel1637575
I have definitely noticed that my skin breaks out whenever I skip out on rest. If I stay up too late staring at my phone, I always wake up with puffy eyes. Is it more about the total hours of sleep or actually sticking to a consistent bedtime every night? redness and stress
I love Gibraltar! We stopped there on a cruise last year. Definitely hike up to the Upper Rock Nature Reserve for the views, but watch your bags around those Barbary macaques https://www.demilked.com/author/sara-ramos95/
Man, this hits home. After a long session in the heat, I easily hit that 5-10 lb sweat loss mark, and my joints definitely feel the toll. I’ve been curious about trying CBD for the inflammation, but I always worry about failing a random drug screen organic CBD for professional athletes
I lived in Peterborough for a few years during my degree and honestly the train to London was a total lifesaver when I needed a quick change of pace. It makes heading down for a weekend trip super easy https://www.inkitt.com/catherine_jackson04
We had sagging gutters inflicting fascia rot; roofing contractor in Millsboro repaired equally efficiently.
As someone in medical billing, the focus on Medicaid fraud always keeps me up at night. Seeing the OIG mention that for every dollar spent on investigations they get back $4.64 really highlights why we are under such a microscope right now https://www.demilked.com/author/raymondphillips87/
Fighting style not only improve physical fitness yet likewise instill self-control and emphasis in experts. It’s fascinating to see just how various designs, from martial arts to jiu-jitsu, deal one-of-a-kind benefits Denver Taekwondo
Great read! I really wish I had checked the CIDB registration of my contractor before starting my last office renovation. It would have saved me so much stress later on industrial style office renovation
This is such a fascinating topic, but it is definitely one that requires careful research. Banking cord blood feels like an insurance policy for peace of mind, though I know the current clinical applications are still limited Ministry of Health Malaysia stem cell bank
I tried out the disagreement tracking feature for my last due diligence report, and it actually caught a few contradictions I would have otherwise missed https://saraclark08.raindrop.page/bookmarks-71945241
I definitely notice a difference in my complexion when I don’t get enough rest. If I stay up late looking at my phone or have a glass of wine, I wake up with puffy eyes and a breakout every single time. It is crazy how much sleep affects our skin health! Website link
I love Gibraltar as a cruise stop! If you visit the Upper Rock Nature Reserve, watch your bags closely around those Barbary macaques. They love grabbing snacks from unsuspecting tourists https://atavi.com/share/xw1xdhz4vdk9
Good to be aware of. bulldog moving company navigated tight staircases devoid of concerns.
I’ve been using CBD after track days because my body really takes a beating pulling 2 to 3 Gs in the corners. It helps take the edge off when I’m finally off the circuit https://lydia-jenkins32.raindrop.page/bookmarks-71945245
If you’re on a tight timeline in Newport News, local movers Newport News VA can schedule fast.
If you’re moving labs or sensitive equipment, ask about vibration control in freight elevators; we learned the hard way until bald eagle movers stepped in.
I appreciated this article. For more, visit ซื้อหวยออนไลน์โปรโมชั่น .
Great review of flat roof fabrics for commercial homes. We’ve mounted highly several TPO and EPDM approaches thru local residential roofers with outstanding performance.
Excellent breakdown of creative constraints by placement. Our cheat sheet is at ecommerce ads agency facebook .
Living in Peterborough really grew on me during my time at the university. It is honestly such a convenient base for trips to London. Taking the train down for a day trip or a job interview is super easy since it is only a 50-minute ride student routine tips
Reliable, fast, and affordable—Rockford moving company found via Rockford moving services .
As someone who manages billing, this push makes me really nervous. We are already dealing with so much overhead, and the OIG finding that they get back $4.64 for every $1 spent on enforcement is going to put a massive target on our backs https://www.protopage.com/nora_zhang00#Bookmarks
Love the twilight exteriors—Houston’s skyline glow really elevates the listing, similar to the dusk sequences I browsed on listing photography spring tx recently.
After last week’s hurricane in Manassas, I needed fast shingle upkeep— Five Stars Roof Replacement had considerable assistance and availability.
Georgetown’s narrow streets made me rethink truck size; a shuttle option from Washington DC movers solved the last-block access issue.
Этот информационный материал подробно освещает проблему наркозависимости, ее причины и последствия. Мы предлагаем информацию о методах лечения, профилактики и поддерживающих программах. Цель статьи — повысить осведомленность и продвигать идеи о необходимости борьбы с зависимостями.
Проверенные методы — узнай сейчас – [url=https://dettka.com/medikamentoznyj-vyvod-iz-zapoya-osobennosti-proczedury/]помощь вывода из запоя[/url]
Visiting Old City and don’t want to deal with parking? I used auto shipping quotes Philadelphia to arrange a quick car service and it was easy.
If your roof hums in top winds, roof replacement in Millsboro can take a look at fastener patterns.