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
}
BSA Insurance claims shows why they are actually the most ideal independent insurance adjusters along with very clear advice and strong results. View BSA Claims Solutions stpetersburg .
Екатеринбург, всем привет Отец не выходит из штопора Родственники не знают что делать Нужна срочная помощь на дому Короче, единственное что вытащило из запоя — капельница от похмелья с витаминами Приехали через 40 минут В общем, телефон и цены тут — капельницы от похмелья [url=https://detoks.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru]капельницы от похмелья[/url] Звоните прямо сейчас Перешлите тем кто в такой же ситуации
I’m really interested in starting therapy but I’m worried about how awkward the first session might feel. It’s not easy opening up to a stranger, especially in person. I’ve thought about online sessions but I’m not sure if they’re as effective https://jsbin.com/pahutihiqi
As a freelance writer, I was particularly interested in the 5 Deep Research queries per day offered in the free plan. That’s a nice touch for someone like me who doesn’t want to overspend but still needs thorough information occasionally Perplexity annual billing
I love the nostalgia around Y2K fashion and how it’s making a comeback! Baby tees are such a fun way to add a playful vibe to any outfit. I’ve seen Bella Hadid style them really effortlessly, pairing with high-waisted jeans for that cool contrast y2k aesthetic
I really appreciate this article shedding light on therapy for men in Vancouver. I’ve been thinking about trying it but worry about having that awkward first session and not knowing what to expect. It’s hard to open up to a stranger Helpful site
I’ve been using Pirate Ship mainly because of the email-only support—it’s been surprisingly efficient for my needs. Also, the $50 credit for free accounts really helped me get started without upfront costs https://wiki-nest.win/index.php/Which_Shipping_Tool_Is_Better_If_I_Need_UPS_Rates_and_Options%3F
I love how you brought back butterfly clips—they were such a fun accessory in the early 2000s! I’ve been seeing them on celebs like Olivia Rodrigo lately, and it’s cool to see something so nostalgic making a comeback https://cashwpkr081.huicopper.com/why-did-y2k-fashion-blow-up-on-search-engines-recently
With havin so much content and articles do
you ever run into any issues of plagorism or copyright violation? My site has a lot of
completely unique content I’ve either authored myself
or outsourced but it looks like a lot of it is popping it up all over the web without my authorization. Do you
know any ways to help stop content from being stolen? I’d definitely appreciate it.
I’ve been using Pirate Ship for a while and really like the $50 credit for eligible free accounts—that gave me a nice boost when I started usps up to 87% off
I love how you brought back butterfly clips—they were such a fun accessory in the early 2000s! I’ve been hesitant to try low-rise jeans again, but after reading this, I’m tempted to give them a shot y2k street style outfits
Thanks for overlaying safe practices alongside steps. Low-glare step lights stepped forward visibility at my place; I deliberate placements with guide from outdoor lighting near me .
I’ve been using Shippo mainly because of their 100+ integrations, which makes syncing with my store super smooth. Pirate Ship’s free plan with a $50 credit sounds tempting, but I’m worried about their email-only support if something urgent comes up thermal label printer software
Well done! Discover more at alojamientos en España familiares .
I really appreciate how Suprmind offers that $19/mo Spark plan with a 7-day trial and no credit card required. It’s nice to try out all the features risk-free https://zulu-wiki.win/index.php/Can_I_Keep_ChatHub_and_Suprmind_Side_By_Side%3F
Здорова, народ Фурнитуру ставят дешманскую То фасады кривые Короче, единственные кто не наваривается — заказ кухни спб недорого Проект бесплатно В общем, смотрите сами по ссылке — ленинградские кухни [url=https://kuhni-spb-lvk.ru]https://kuhni-spb-lvk.ru[/url] Не ведитесь на салоны-прокладки Перешлите тому кто ищет
I’ve been trying out Suprmind for a few weeks, mainly because of the $39 lifetime option, and I really like the Debate mode for clarifying complex thoughts decision brief generator
I think this is one of the most significant information for me.
And i’m glad reading your article. But should remark on some general things, The
website style is wonderful, the articles is really nice
: D. Good job, cheers
I’m really impressed that Suprmind offers a 7-day trial with no credit card required. It makes testing out their features like the Red Team and cookie passthrough so much less stressful Great site
Слушайте, кто реально сталкивался с такой бедой? Брат снова жестко сорвался после долгого перерыва, Соседи уже стучат в стену и грозятся вызвать полицию, Никакие народные методы и таблетки из аптеки вообще не помогают пока чисто случайно не наткнулся на экстренных наркологов с лицензией, и обеспечивает быстрый выезд специалистов со всем необходимым оборудованием. Сразу профессионально поставили капельницу с детоксикационным раствором,
В общем, если не хотите тратить время на самостоятельные тесты, вся полезная инфа выложена вот здесь прокапаться от запоя [url=https://nedorogoy.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru]https://nedorogoy.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru[/url] Квалифицированная медицинская помощь на дому — это единственный реальный выход, обязательно перешлите этот пост тем, кто тоже сейчас находится в такой же критической ситуации!
Народ всем привет Фурнитуру ставят китайскую То фасады кривые Короче, единственные кто не наваривается — кухни СПб от производителя напрямую Сделали за две недели В общем, смотрите сами по ссылке — кухни под заказ [url=https://kuhni-spb-qmz.ru]кухни под заказ[/url] Проверяйте производителя по этому списку Перешлите тому кто ищет
выберите ресурсы [url=https://vodkabet-vb.com/]водка бет[/url]
I’ve been trying both Suprmind and TypingMind for a few weeks—Suprmind’s $19/month plan feels like a solid deal for the features, especially the Debate mode, which really helps clarify complex topics Informative post
Hello! I just wanted to ask if you ever have any problems with hackers?
My last blog (wordpress) was hacked and I ended up losing
several weeks of hard work due to no backup.
Do you have any solutions to prevent hackers?
I’ve been testing both Suprmind and MultipleChat for a few weeks—really appreciate that Suprmind offers over 25 templates, which makes it easier to get started quickly https://city-wiki.win/index.php/Which_Tool_Is_Better_If_I_Need_Image_Generation_Across_8_Models%3F
I really appreciate that Suprmind offers a 7-day trial with no credit card required—that’s a huge plus for me when testing new AI tools. ChatHub seems cool but having that kind of risk-free access makes Suprmind feel more user-friendly ChatHub alternative
Packing fragile kitchenware was my biggest worry. The West Hartford team we found on West Hartford commercial movers brought dish barrels and it was a game changer.
I appreciated this post. Check out web para mascotas for more.
I’ve been using Suprmind for a few weeks, mainly for the Debate mode, and it’s surprisingly thorough at exploring different viewpoints https://scott_lopez02.raindrop.page/bookmarks-73346274
Люди, помогите дельным советом. Муж просто потерял себя и уничтожает свое здоровье. Родственники в панике и вообще не знают, что делать. В обычную государственную больницу тащить человека просто страшно до тех пор, не наткнулся на экстренных наркологов с лицензией, и обеспечивает быстрый выезд специалистов со всем необходимым оборудованием. Уже через пару часов человек наконец-то пришёл в себя и уснул,
Кому тоже экстренно необходим проверенный круглосуточный телефон наркологии, вся полезная инфа выложена вот здесь капельница от похмелья клиника [url=https://nedorogoy.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru]капельница от похмелья клиника[/url] Квалифицированная медицинская помощь на дому — это единственный реальный выход, обязательно перешлите этот пост тем, кто тоже сейчас находится в такой же критической ситуации!
I’ve been testing Suprmind’s Red Team mode and noticed it really helps in catching biases before deploying, which MultipleChat doesn’t seem to offer per-claim verification for reports
Removing a tree safely takes skill and planning. This was a great read for anyone considering tree service. More resources: lawn care
This was highly helpful. For more, visit divorce mediator .
I’ve tried both Suprmind and MultipleChat, and I noticed Suprmind’s $19 Spark plan includes access to five different models, which is pretty flexible. However, I found the lack of PPTX export a bit limiting when I wanted to create presentations quickly AI orchestration platform for teams
I’ve been using Suprmind’s Decision Validation Engine, and it’s a game-changer for making confident choices without second-guessing. The $19 monthly plan feels totally worth it for that feature alone Helpful site
Народ, кто в Питере? Цены гнут просто космос, а качество материалов как мыло, То плита ЛДСП слишком тонкая и рыхлая до тех пор, не наткнулся на местных ребят со своим технологичным цехом, начиная от разработки детальной схемы и заканчивая финальным монтажом. Полностью изготовили весь комплект всего за две недели.
В общем, если не хотите переплачивать салонам-прокладкам, жмите на источник, чтобы случайно не потерять контакты кухни на заказ в спб каталог [url=https://zakazat-kuhnyu-jep.ru]https://zakazat-kuhnyu-jep.ru[/url] Всегда заказывайте корпусную мебель напрямую у завода-изготовителя, обязательно перешлите этот пост тому, кто тоже сейчас ищет качественную мебель! Сам долго мучался, теперь делюсь проверенным местом.
I’ve been using Suprmind’s Decision Validation Engine, and it’s a game-changer for making more confident calls on projects. The $19/month plan feels like great value given how much time it saves me what is Debate mode AI
Люди помогите советом Задолбался я уже искать нормальную кухню То фасады кривые Короче, нашел наконец нормальное производство — кухни СПб от производителя напрямую Сделали за две недели В общем, сохраняйте в закладки — кухни на заказ производство спб [url=https://kuhni-spb-qmz.ru]кухни на заказ производство спб[/url] Не ведитесь на салоны-прокладки Сам мучался теперь делюсь
I’ve been using Suprmind’s Decision Validation Engine for a few weeks now, and it really helps me avoid costly mistakes by checking my logic step-by-step. For $19 a month, it’s been a solid investment compared to other AI tools I’ve tried https://able-nannyberry-e02.notion.site/Suprmind-offers-a-unique-Decision-Validation-Engine-to-help-teams-make-more-3aaaa7bc25e180c7bcf5fe8345dde7e6
Just had an emergency after-hours burst pipe in Feasterville—calling a 24/7 Plumber Feasterville via plumber feasterville saved my basement.
Tree care is one of those home maintenance tasks that should not be ignored. Safety and appearance both benefit from it. Visit lawn service .
As a freelance writer, I’m really interested in the 5 Deep Research queries per day included in the basic plan. That feature seems like a solid way to dig into topics without quickly hitting a paywall sonar deep research vs pro
В данном обзоре представлены основные направления и тренды в области медицины. Мы обсудим актуальные проблемы здравоохранения, свежие открытия и новые подходы, которые меняют представление о лечении и профилактике заболеваний. Эта информация будет полезна как специалистам, так и широкой публике.
Слушай внимательно — тут важно – [url=https://lux-clinic.ru/kapelnitsa-ot-zapoya/]капельница от запоя[/url]
Don’t forget to measure doorways! We uploaded dimensions to Champlin movers services so our Champlin movers could plan disassembly.
This was highly educational. More at precios abogado Coruña .
This was a fantastic read. Check out indemnización por despido for more.
As a freelance writer constantly juggling multiple projects, I really appreciate that Perplexity offers 5 Deep Research queries per day—it’s a great way to dive into complex topics quickly without breaking the bank https://domgodwinson38.gumroad.com/p/how-many-files-can-i-put-in-a-perplexity-space-on-pro-50-files
As a freelance writer, I’m intrigued by the 5 Deep Research queries per day included in the free plan—that’s generous for quick fact-checking! However https://mrpbw.stick.ws/
С пациентом работают профильные специалисты, которые оценивают состояние и подбирают безопасный план помощи.
Детальнее – [url=https://vyvod-iz-zapoya-v-anape6.ru/]вывод из запоя капельница[/url]
Народ, кто в Питере? Задолбался я уже искать нормальную кухню для квартиры, То сроки изготовления выставляют чуть ли не по полгода пока чисто случайно не наткнулся на местных ребят со своим технологичным цехом, начиная от разработки детальной схемы и заканчивая финальным монтажом. Итоговые цены получились ниже розничных салонов минимум на 30%,
В общем, если не хотите переплачивать салонам-прокладкам, там представлены реальные проекты с ценами мебель для кухни каталог [url=https://zakazat-kuhnyu-jep.ru]мебель для кухни каталог[/url] Лучше сразу выбирать проверенную фабрику с официальной гарантией. обязательно перешлите этот пост тому, кто тоже сейчас ищет качественную мебель! Сам долго мучался, теперь делюсь проверенным местом.