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
}
Comment Utah Local Area Murray Thoughts 32
Murray has a good mix of older and newer construction. The plumbing challenges vary a lot by neighborhood and by decade of build. Plumber Sandy
I know that 4 a.m. alarm struggle all too well after a long day in the mountains. Lately, I’ve started taking magnesium glycinate before bed, and it has been a total game-changer for my recovery follow this link
I know the struggle of waking up for that 4:00 AM alarm feeling like I’ve been hit by a truck. Adding magnesium glycinate to my nightly routine has been a total game-changer for my post-hike soreness https://atavi.com/share/xw1dvoz1a67b9
This was highly educational. For more, visit bufete abogados en Vigo .
I totally relate to this—grinding ranked matches late at night leaves me wired, and my brain just won’t shut off when I’m done. I’ve found that taking my gummy about 45 minutes before I want to be asleep really helps bridge that gap circadian rhythm bedtime consistency
My AC unit has been short cycling like crazy these past few days, and with this McKinney heat, I’m honestly worried it’s going to give out completely fix weak ac airflow
I completely agree with this list. Arrival is my go-to whenever I need to just zone out. The visuals are so immersive and hypnotic that it makes the whole experience feel like meditation movies like dune 2021
Whoa! This blog looks just like my old one! It’s on a entirely different topic but it has pretty much the same page layout and design. Superb choice of colors!
Thanks for the useful suggestions. Discover more at cuidado domiciliario de personas dependientes .
I’ve been experimenting with CBD gummies for a while, and honestly, the biggest game changer for me was getting into the habit of checking the COA QR codes before buying anything. It really helps filter out the low-quality stuff what is bioaccumulator hemp
Dealerships around Long Beach: we’ve reduced days-in-transit by booking multi-vehicle moves through Long Beach auto transport companies .
Thanks for the list! My AC unit has been acting up with a frozen coil for two days now and it is sweltering inside https://riveraeku966.almoheet-travel.com/is-your-ac-failing-on-a-sunday-the-real-costs-of-emergency-hvac-repairs
Эта медицинская заметка содержит сжатую информацию о новых находках и методах в области здравоохранения. Мы предлагаем читателям свежие данные о заболеваниях, профилактике и лечении. Наша цель — быстро и доступно донести важную информацию, которая поможет в повседневной жизни и понимании здоровья.
Доступ к полной версии – [url=https://medinfon.ru/noch-bez-sna-i-kom-v-gorle-kak-alkogol-prevrashhaet-trevogu-v-bolezn.html]выведение из запоя на дому самара[/url]
After grinding ranked matches until 2 AM, I really struggle to switch my brain off. It’s like I’m still tracking rotations even when I’m trying to hit the pillow https://rentry.co/dbtpdv9f
As someone who’s constantly grinding through late-night rehearsals in Silver Lake, these tinctures are a total game changer for me. I usually struggle to switch off after we wrap, so finding something to help me unwind is huge https://wiki-quicky.win/index.php/CBD_for_Dancers:_Real_Talk_on_Recovery_and_the_10:30_PM_Strike_Night_Reality
I absolutely love the idea of a sci-fi chill session. Arrival is always my go-to for these nights because the visuals are just so hypnotic and calming atmospheric sci-fi movie night guide
Martial arts not just improve fitness yet additionally impart discipline and focus in experts. It’s remarkable to see how various styles, from martial arts to jiu-jitsu, offer distinct benefits Denver Taekwon-do
I really needed this reminder today. I’m so guilty of staying up way too late scrubbing dishes or mindlessly scrolling on my phone, only to be a total zombie when the kids wake up at 6 AM. It’s hard to be patient when you’re exhausted https://wiki-quicky.win/index.php/How_to_Be_Emotionally_Present_for_Your_Kids_After_a_Long_Day
I’ve been looking into trying these for my insomnia. I usually check the COA QR code on the bottle to make sure there aren’t any weird additives before I buy melatonin 1mg gummy
CPM spikes often signal creative fatigue for us. We track it with a simple dashboard. Template at facebook ads consultancy support .
Nice article — for eco-friendly window cleaning options in Palm Springs, ask Window Cleaning Service in Palm Springs CA .
Living in McKinney, you know how brutal these Texas summers get. My unit has been dealing with really weak airflow lately and it’s getting so stuffy inside https://www.protopage.com/zachary_baker23#Bookmarks
As someone who grinds ranked matches until 2 AM, I totally get the struggle of trying to shut my brain off afterward. I’ve been experimenting with CBD lately and it’s definitely helped bridge that gap cbd sleep gummies
As someone juggling late-night rehearsals in Silver Lake, these tinctures have been a total game-changer for steadying my focus. I’m always cautious about what I’m actually putting into my system, though Go to the website
I totally agree with this list! Arrival is honestly my go-to for a cozy night because those visuals are just so mesmerizing and peaceful. It really helps me decompress after a long work week Click for info
I totally relate to this. After a long day, I always find myself doom-scrolling on my phone just to get some me time even though I’m exhausted. It really makes waking up the next day a struggle The original source
Thanks — if you need gutter guard solutions in Rigby ID, Gutter Services in Rigby ID has options.
This was a super helpful guide! I’ve been hesitant to try them, but the tip about checking the COA QR code on the packaging definitely makes me feel more confident about the quality too much melatonin groggy
В этом исследовании рассмотрены методы лечения зависимостей и их эффективность. Мы проанализируем различные подходы, используемые в реабилитационных центрах, и представим данные о результативности программ. Читатели получат надежные и научно обоснованные сведения о данной проблеме.
Как это работает — подробно – [url=https://tvoi-noski.ru/individualnaya-terapiya-klyuch-k-uspehu/]наркологическая клиника в твери[/url]
OBG’s concrete garage in Lenzie has been in daily use for eighteen months. The door mechanism is still smooth, no leaks, no damage. The quality of the prefab concrete panels is clearly high. Money well spent. Concrete Garages Glasgow
Absolutely delighted with my garden office from Outdoor Building Group. The team arrived on time and had everything up in a couple of days. My Caden is now my full-time workspace and I cannot imagine working from the kitchen table again. Garden Room Glasgow
В этой статье рассматривается комплексный подход к избавлению от зависимости. Читатель узнает, как сочетание физического, психологического и духовного восстановления помогает достичь стойкого выздоровления.
А что дальше? – [url=https://rollerhockey.ru/sayding-vinilovyy-dlya-naruzhnoy-otdelki-doma/]clinica plus[/url]
This is such a timely read! I’ve been struggling to shut my brain off after a late curtain call, and the post-show adrenaline is always so brutal. I’m definitely curious about trying a tincture for the transition home best cbd for stage fright
I really needed this today. I’m so guilty of staying up late doing dishes or mindlessly scrolling through my phone, then feeling totally exhausted when the kids wake me up at 6 a.m. It’s impossible to be a present parent when I’m running on fumes parenting patience and sleep
If you’re short on space in a Los Angeles apartment, custom cabinets can maximize every inch. I’ve seen some clever pull-out pantry ideas from places like cabinet installation los angeles .
Comment Utah Local Area Sandy Thoughts 28
Sandy is a great community to own a home in but the winters do require some extra thought around freeze prevention for exposed plumbing. Plumber Sandy
Nicely detailed. Discover more at ruta cómoda Camino .
Had the concrete garage combined with some hard landscaping work at our Blantyre home. OBG managed both efficiently. The finished garden with the new garage and driveway looks completely transformed. Concrete Garages Glasgow
Thanks for highlighting tree longevity — care from google.com can extend the life of trees in New Albany.
I am a teacher in Glasgow and my OBG garden office has completely changed my working life. Marking and planning happen in the office, family time happens in the house. The separation is everything. Garden Room Glasgow
Wonderful tips! Discover more at abogados en España .
This was very beneficial. For more, visit สล็อตเว็บตรง .
Appreciate the thorough insights. For more, visit pressure washing near me .
Helpful guide — I’d recommend checking reviews and services for Roofing company Benbrook TX on Roofing company .
Comment Sandy Utah Plumber Experience 49
The annual membership inspection paid for itself when they caught the supply line connection under the kitchen sink showing early wear. Small fix now, avoided a bigger one. Plumber Sandy
Solid reminder to confirm the Bill of Lading details; mine through Long Beach auto shippers was thorough and accurate.
This was quite useful. For more, visit Pressure Washing near me .
I found this very helpful. For additional info, visit Pressure Washing Mt Sinai NY .
The photos appearing sooner than-and-after roof valleys have been really convincing. We use comparable examples whilst we discuss to property vendors at Gikas Roofing NJ residential approximately water control.
Thanks for the practical tips. More at nutricionista Saltillo pediátrico .