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
}
This was highly useful. For more, visit nutricionista en Saltillo online .
Szukałem skutecznego sposobu na dotarcie z reklamą kliniki do rodziców małych dzieci, stąd rekomendacja dla Proboost z Warszawy, ul. Hoża 86/410. Kampanie reklamowe i doradztwo marketingowe przyniosły widoczne efekty. Doradca marketingowy
This was highly useful. For more, visit https://privatebin.net/?1061aa9a4303acac#hzdruSzveThomK2iXkno2dEEuHtwFWh1ih2RZaND7Vz .
This was highly informative. Check out Xeira catálogo for more.
Thanks for the detailed post. Find more at abogados en Vigo de familia .
Great tips! For more, visit http://www.ybcxz.com/link.php?url=https://blogfreely.net/petramzdrt/sunday-roast-and-brunch-keywords-targeting-weekend-break-diners .
Get ergonomic evaluations after the move to reduce injury claims. We scheduled assessments using guidance from movers brentwood tn .
The staging advice helped sell our home faster. After staging, Cumming moving companies stored excess furniture until closing.
For anyone in Houston needing quick car key replacement, I had a smooth experience—see commercial lockset installation Houston .
Great job! Discover more at latest tubidy mp3 releases .
The timeline for curing finishes is useful. For careful finishing in Charlotte, residential flooring contractor Charlotte did an amazing job.
I lately learned how elaborate Washington’s wrongful dying regulations can be, notably for grieving households in Everett website here
Pracując jako freelancer IT, szukałem kogoś, kto pomoże mi ułożyć strategię i ruszyć z pozyskiwaniem zleceń, polecam Proboost przy ul. Hożej 86/410 w Warszawie każdemu, kto prowadzi podobną działalność Doradca marketingowy
Этот документ охватывает важные аспекты медицинской науки, сосредотачиваясь на ключевых вопросах, касающихся здоровья населения. Мы рассматриваем свежие исследования, клинические рекомендации и лучшие практики, которые помогут улучшить качество лечения и профилактики заболеваний. Читатели получат возможность углубиться в различные медицинские дисциплины.
Практические советы ждут тебя – [url=https://belady.online/house/kogda-privychka-stanovitsya-ugrozoj-poshagovoe-rukovodstvo-dlya-zhenshhin-kak-spasti-blizkogo-cheloveka-ot-alkogolnoj-zavisimosti/]платная скорая вывод из запоя[/url]
Anyone moving near downtown Harrisburg? Harrisburg apartment moving services covers parking permits and access tips.
В статье по вопросам здоровья мы рассматриваем актуальные проблемы, с которыми сталкивается общество. Обсуждаются заболевания, факторы риска и важные аспекты профилактики. Читатели получат полезные советы о том, как сохранить здоровье и улучшить качество жизни.
Почему это важно? – [url=https://lifepeople.info/novosti/gran-mezhdu-xronicheskoj-ustalostyu-i-zavisimostyu-kak-vovremya-raspoznat-skrytyj-krizis-u-blizkogo-cheloveka/]срочно врач нарколог на дом[/url]
В этой публикации мы обсуждаем современные методы лечения различных заболеваний. Читатели узнают о новых медикаментах, терапиях и исследованиях, которые активно применяются для лечения. Мы нацелены на то, чтобы предоставить практические знания, которые могут помочь в борьбе с недугами.
Узнать из первых рук – [url=https://materinstvo2.com/kak-podderzhat-blizkogo-cheloveka-pri-alkogolnoj-zavisimosti-i-sohranit-spokojstvie-v-seme/]частный нарколог на дом москва[/url]
If you’re moving pets, note that many Arlington buildings have breed and weight limits. We verified policies ahead of time with help from movers arlington va .
Emergency response times can be a dealbreaker. I checked average response metrics on tree removal service .
This was a wonderful post. Check out tubidy mp3 ringtone download for more.
Great insights on dealing with production debris! For all of us in Lee County tackling a redesign or cleanout why not try these out
מעולה. דרך משכנתא לגיל השלישי למדתי על מסלולים צמודים ולא צמודים והשלכות המדד.
“Your post helped me understand why regular maintenance is critical during off-peak seasons!” Find additional details at Swim and Spas .”
Ugh, tell me about it. We’ve been dealing with our system short cycling constantly lately, especially with how hot it’s been out here in McKinney. It’s brutal ac maintenance mckinney
da88t.de.com mang đến môi trường giải trí trực tuyến với nhiều nội dung đặc sắc, hệ thống trò chơi được cập nhật liên tục và các chương trình ưu đãi diễn ra thường xuyên bbc
Эта доказательная статья представляет собой глубокое погружение в успехи и вызовы лечения зависимостей. Мы обращаемся к научным исследованиям и опыту специалистов, чтобы предоставить читателям надежные данные об эффективности различных методик. Изучите, что работает лучше всего, и получите информацию от экспертов.
Дополнительно читайте здесь – [url=https://divoch.ru/ostroe-otravlenie-chto-delat-do-priezda-medikov-poshagovyy-protokol/]вызов нарколога на дом в москве цена[/url]
Living here in McKinney, the heat is no joke, especially when your system starts acting up. My AC unit has been short cycling like crazy lately, and I’m honestly dreading a total breakdown https://privatebin.net/?858dcc2e6085244c#A664ejgdoYDVyBRvgquDUgnc2BmnU9RazdvRtmoXqhsa
It’s really interesting to see so much capital flowing into the self-storage market lately. I’ve noticed a few new facilities popping up in my area, which makes me wonder if supply is catching up to demand too quickly self storage security systems
Thanks for this post, it is really helpful to know these steps in Arizona. I was involved in a minor fender-bender last year and forgot to take photos of the surrounding intersection, which caused some issues later https://high-wiki.win/index.php/Insurance_offered_a_quick_settlement_-_should_I_take_it%3F
Living here in McKinney, we definitely know how brutal these summers can get. My unit started blowing warm air just yesterday, which is the last thing I need right now Visit this page
Публикация охватывает основные направления развития современной медицины. Мы обсудим значимость научных исследований, инноваций в лечении и роли общественного участия в формировании системы здравоохранения.
Погрузиться в научную дискуссию – [url=https://clubsamodelok.ru/kak-vosstanovit-sily-posle-intensivnoj-klubnoj-nochi-poleznye-sovety-i-opyt-specialistov/]вызвать нарколога на дом недорого москва цены[/url]
I appreciated this article. For more, visit tubidy free download .
After my own accident a few years back, I know how overwhelming the legal side of things can be when you’re just trying to recover https://uniform-wiki.win/index.php/Is_there_a_Phillips_Law_Group_blog_I_can_read_before_calling%3F
Thanks for the detailed post. Find more at tubidy online .
It’s really interesting to see so much capital pouring into the UK self-storage market lately. I’ve noticed a few new facilities popping up in my area, which makes me wonder if the local demand is actually keeping pace with all this new supply self storage sector growth uk
Being involved in a crash here in Arizona is so overwhelming, but these steps make the process much clearer https://beauoynz053.lucialpiazzale.com/what-questions-should-i-ask-before-signing-with-an-injury-lawyer
Get multiple bids to compare apples to apples. I organized quotes with a worksheet from professional tree removal .
After my own fender bender last year, I realized how overwhelming the legal side of things can be. It’s tough to find the right representation when you’re still recovering https://blogfreely.net/neasalnfbo/h1-b-how-far-is-tucson-from-phoenix-for-their-tucson-office-navigating-your
”Engaging deeply enhances understanding surrounding potential paths taken yields fruitful discussions benefiting everyone involved ultimately!” ## Clear Braces
If you’re decluttering before moving, a 15-yard bin is nice— roll off dumpster rental services Scottsdale, AZ can help you pick.
It’s really interesting to see so much capital flowing into the UK storage market lately. I’ve noticed a few new facilities popping up in my area, which makes me wonder how crowded the sector is actually getting automated self storage technology
В данной статье рассматриваются физиологические и эмоциональные аспекты зависимости. Мы обсудим, как организм реагирует на зависимое поведение, и какие методы помогают восстановить здоровье и внутреннее равновесие.
Выяснить больше – [url=https://ladyup.ru/moda/kapelnicza-posle-alkogolya-doma-kogda-eto-pomoshh-a-kogda-opasnyj-mif.html]выведение из запоя на дому воронеж[/url]
This is really helpful information to keep in mind, especially since driving in Phoenix can get so stressful. I never thought about taking photos of the debris field itself, not just the car damage https://tr.ee/3FDE52y9mg
I found this very interesting. For more, visit http://www.fcviktoria.cz/media_show.asp?id=2924&id_clanek=2467&media=0&type=1&url=https://josuecqtw454.fotosdefrases.com/menu-seo-how-your-online-food-selection-impacts-your-rankings .
I read this article and considered buying the $15 for 2500 likes package. It sounds tempting because the site claims no password required for the delivery. However, I worry about Instagram flagging my account for fake engagement https://direct-wiki.win/index.php/If_I_Buy_Likes,_Should_I_Also_Improve_Captions_and_Posting_Schedule%3F
I was looking into this recently after a minor fender bender on the I-10. It’s definitely overwhelming trying to figure out where to start. I appreciate you pointing out that they offer virtual appointments Spanish speaking injury lawyer Phoenix
This became first rate important—surprisingly the repairs details. For all and sundry considering that lash extensions in Corpus Christi, ask approximately humidity-proof adhesives and e book fills every 2–three weeks to retain them clean check this link right here now
Excellent post. I was checking continuously this blog and I am impressed!
Very useful information specifically the last
part :) I care for such info much. I was seeking this certain info
for a very long time. Thank you and good luck.
Zależało mi na dotarciu do szkół muzycznych i orkiestr przez wyszukiwarkę, polecam Proboost przy ul. Hożej w Warszawie jako sprawdzone wsparcie marketingowe. Strategia SEO i badanie słów kluczowych okazały się strzałem w dziesiątkę. Doradca marketingowy
I read this post and it really makes me wonder if buying likes is worth the risk. I saw a site offering 2500 likes for $15, which sounds tempting, but I worry about the safety of my data organic instagram growth services review