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
}
einzahlungsbonus nach anmeldung
Also visit my web site :: casino mit den besten cluster pays
online casino ohne wartezeit paysafecard
Here is my web page; Spielautomaten Mit Usdt
Hello it’s me, I am also visiting this website on a regular basis, this
web site is really nice and the visitors are in fact sharing fastidious thoughts.
best online horse oxford greyhound racing fixtures (Scott) betting
Wow, this article is fastidious, my younger sister is analyzing such things, so I am going to
inform her.
This article is a good reminder that every lawn has different needs. Soil type, shade, and climate should all be considered. Resource: weed control company
Thanks for another informative site. The place else may I am getting
that type of info written in such an ideal means? I’ve a challenge
that I am simply now working on, and I’ve been at the look out for such information.
אהבתי את הדגש על עמידה ביעדי תזרים. כלי מעקב ב- משכנתא לפנסיונרים .
Weeds can take over quickly if they are not managed early. Homeowners may want to consider professional weed control services through weed control company .
Люди подскажите Замучился я уже искать информацию по участкам Соседи какие Короче, работает быстро и бесплатно — публичная кадастровая карта с поиском по номеру Нашёл участок за 5 минут В общем, жмите чтобы не потерять — пкк карта [url=https://publichnaya-kadastrovaya-karta-abc.ru]https://publichnaya-kadastrovaya-karta-abc.ru[/url] Не мучайтесь с росреестром Перешлите тому кто ищет участок
This article is a good reminder that not all moving companies offer the same level of service. It’s worth looking for movers who are professional, punctual, and transparent. Everett Mover’s
I think local movers are especially valuable because they understand area-specific challenges like parking, building access, and timing. For Marietta moves, Long distance movers Marietta may help.
בדקנו מול הבנק עם היועץ וקיבלנו תנאים טובים בהרבה. לפרטים נוספים: ייעוץ להבראה כלכלית
Discover Kaizenaire.com, Singapore’ѕ premier hub fоr the most
reⅽent shopping deals, promotions, ɑnd special event supplies customized fоr wise
customers.
In thе midst ᧐f Singapore’ѕ shopping heaven, Singaporeans bond ᧐ver common promotions.
Singaporeans love organizing themed celebrations fоr special
occasions, аnd remember to гemain upgraded
ⲟn Singapore’s most current promotions аnd shopping deals.
TWG Tea supplies gourmet teas ɑnd accessories, valued Ƅy tea aficionados
in Singapore fοr tһeir charming blends аnd elegant product packaging.
Weekend Sundries develops wɑy of life accessories ⅼike bags sіa,
valued by weekend travelers іn Singapore for thеіr practical
style lah.
ABR Holdings operates Swensen’ѕ and ѵarious other dining establishments,
enjoyed ffor varied dining chains tһroughout Singapore.
Eh, wһy delay lor, Singaporeans neеd to surf
Kaizenaire.ϲom everyday mah.
My web site :: mortgage loan promotions (http://kopac.co.kr/xe/index.php?mid=board_qwpF53&document_srl=2878001)
whoah this weblog is great i like studying your articles.
Keep up the great work! You understand, lots of people
are hunting around for this information, you
could help them greatly.
I am really impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you modify it yourself? Anyway keep up the excellent quality writing, it’s rare to see a nice blog like this one today.
Attractive section of content. I just stumbled upon your website and in accession capital to assert that
I get in fact enjoyed account your blog posts. Any way I’ll be subscribing
to your augment and even I achievement you access consistently
rapidly.
Very informative post about maintaining a healthy lawn. I especially liked the reminder about regular aeration and fertilization. Relevant resource: lawn care
Removing hazardous branches before they fall is always the right move. Preventive tree care is much better than emergency repairs. More details at lawn care .
Excellent blog here! Also your web site
a lot up very fast! What host are you using?
Can I am getting your associate hyperlink in your host?
I want my website loaded up as quickly as yours
lol
Fantastic beat ! I wish to apprentice at the same time as you amend your
website, how can i subscribe for a blog web site?
The account helped me a acceptable deal. I were a little
bit familiar of this your broadcast provided shiny transparent concept
spielautomat hacken
Also visit my page :: online casino mit 75 freispielen
seriöses casino freispiele ohne ersteinzahlung turnier preisgeld
I loved as much as you will receive carried out right here.
The sketch is tasteful, your authored subject matter stylish.
nonetheless, you command get got an edginess over that you wish be
delivering the following. unwell unquestionably
come further formerly again as exactly the same nearly a
lot often inside case you shield this increase.
סוף סוף שליטה בכרטיסי האשראי – הודות ל- הלוואות לאיחוד למשכנתא .
Good article for anyone planning a move in Everett. Decluttering before moving day and packing essentials separately can make the whole experience much easier. Everett moving companies
Planning ahead is key for any Marietta move, especially during busy weekends or end-of-month schedules. Local movers Marietta can be a good resource for finding local moving help.
Быстро собираем первичную информацию, оцениваем риски и предлагаем подходящий вариант обращения.
Получить дополнительные сведения – [url=https://narkolog-na-dom-v-novorossijske3.ru/]врач нарколог на дом[/url]
This post gives a clear overview of why professional weed management matters. The right plan can reduce weeds and improve lawn resilience. Visit: lawn service
Tree removal is not something homeowners should attempt without proper tools and knowledge. This post explains that well. tree service is another helpful resource.
http://www.rando-cretes.fr/media/pgs/code_promo_1xbet_aujourdhui.html
Wow! This blog looks just like my old one! It’s on a totally different topic but it has pretty
much the same page layout and design. Wonderful choice of colors!
Thanks for sharing. I like that you mentioned regular maintenance because weeds are easier to manage before they spread. tree service is a good resource for those needing assistance.
A good lawn care routine can prevent weeds, uneven growth, and messy outdoor spaces. For helpful service information, check lawn care .
I always emailed this webpage post page to all my associates, as if like to read it next my links will too.
A reliable moving company can make an overseas relocation much easier. Anyone in the Waterbury area looking into international moving services can visit Waterbury commercial movers
Thanks for sharing this information. Many people forget to ask movers about packing supplies, travel fees, and minimum charges. cross state movers can be useful for finding cheap movers Oakland without overlooking important details.
Long-distance moves require trust, communication, and good timing. If you’re looking for Long distance movers Redwood City, visit out of state movers Redwood City .
I don’t know if it’s just me or if everybody
else encountering problems with your blog. It appears as though some of the text within your posts are running off the screen. Can somebody else please comment and
let me know if this is happening to them too?
This may be a problem with my browser because I’ve had this happen before.
Kudos
Wonderful blog! I found it while browsing on Yahoo News.
Do you have any tips on how to get listed in Yahoo News?
I’ve been trying for a while but I never seem to get there!
Thanks
Moving an office is not the same as moving a home. Desks, computers, printers, and documents all require careful handling by trained Dacula office movers. Dacula moving company
Moving day goes much better when you have experienced movers handling the heavy lifting. Hampton moving companies can be a great solution for homes, apartments, and businesses. Visit Local movers Hampton for more.
Office moving companies in Lawrence can be especially helpful for businesses that want to avoid interrupting daily operations. Lawrence moving company
https://therockpit.net/wp-content/pages/melbet_free_promo_code_enter__.html
This is very interesting, You are a very skilled blogger.
I have joined your rss feed and look forward
to seeking more of your fantastic post. Also, I’ve shared your
site in my social networks!
I always recommend getting organized early when planning a long-distance move. For those in Allentown, Local movers Allentown is worth checking out.
I appreciate these practical moving suggestions. Local knowledge is a big advantage when hiring Redlands movers because they understand traffic, parking, and neighborhood access. Another helpful place to check is moving company Redlands .
Very soon this website will be famous among all blogging and site-building viewers, due to it’s fastidious articles or reviews
If anyone’s looking for reliable local movers in Tampa, I had a smooth experience and would recommend checking Local movers Tampa before booking.
Curious about terminal storage fees near Stockton if delivery is delayed—saw fee charts linked at Stockton vehicle shipping .