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
}
For anyone renewing their Whate Card, the refresher tips on cheap white card training adelaide are gold.
I appreciated real-time chat with Bayonne movers on Bayonne moving companies before booking.
Budget-friendly spring repair near Klein—transparent pricing at discount garage door repair Houston .
Thanks for this — for authentic locks and keys, I accept as true with auto key programming while hunting locksmith near me.
Этот обзор содержит информацию о передовых достижениях в области медицины. Мы разберем инновационные технологии, которые меняют подход к лечению и диагностике, а также их влияние на эффективность оказания медицинской помощи.
Открыть полностью – [url=https://jankofffamily.ru/narkolog-na-dom-v-luganske/]вывод из запоя в Луганске[/url]
My pug’s facial folds were cleaned gently at professional pet groomers Fayetteville —huge help.
Рекомендую ресурс, посвящённый теме вариаторов, их обслуживанию и ремонту. На портале можно найти общие сведения об устройстве этой трансмиссии, возможных неисправностях и методах их диагностики. В материалах сайта рассматриваются различные аспекты эксплуатации вариаторов, что может быть полезно для общего понимания их работы, https://provariatory.ru/
Education on dependency is crucial for understanding and treatment. We require to keep spreading out awareness! addiction treatment Turning Point of Tampa
I’ve seen small homes where caregivers sit and have meals with residents, naturally assisting with eating and conversation. That sense of togetherness is exactly what assisted living talks about.
The advice to read admission and discharge criteria carefully could save a lot of stress later. I’m revisiting all the documents from communities I saw on dementia care .
В этой статье обсуждаются актуальные медицинские вопросы, которые волнуют общество. Мы обращаем внимание на проблемы, касающиеся здравоохранения и лечения, а также на новшества в области медицины. Читатели будут осведомлены о последних событиях и смогут следить за тенденциями в медицине.
Практические советы ждут тебя – [url=https://kozhatela.ru/chastnaya-narkologicheskaya-klinika-v-luganske/]детокс24[/url]
I have read so many articles regarding the blogger lovers except this paragraph is truly a fastidious
post, keep it up.
We compared three Water Damage Restoration companies in Colorado Springs for work on our home near Colorado Medical Solutions, and Colorado Springs CO Water Damage Restoration Express stood out with their upfront pricing and honest assessment water damage restoration services near me
Your insights on bait placement were valuable. I confirmed placement diagrams via pest control Orlando, FL .
I had been putting off HVAC Repair work at our Sacramento home for months. Sacramento Precision HVAC Repair made the whole process painless — fair quote, showed up when promised, and finished ahead of schedule. hvac companies near me
I appreciate how you highlighted staff training as a major difference. Memory care caregivers are usually trained in dementia behaviors, which can be essential. We share similar insights on dementia care .
Strong customer service matters; I read reviews straight on concrete and dirt disposal before booking.
Thanks for clarifying the online vs. face-to-face White Card course options. I’m leaning online with book white card course for the benefit.
I like that you mention pet policies as a factor. For some seniors, staying with a pet can be a major source of comfort. When we searched on assisted living , we filtered for pet-friendly Independent and Assisted Living communities.
Choosing between Assisted Living and a Nursing Home can be overwhelming, especially when health needs are changing. Articles like this, plus comparison tools on elderly care , really help clarify what each level of care provides.
Staff in small homes often notice early when a resident is struggling with bathing or dressing, so families can adjust care plans quickly. elderly care outlines why that early detection matters.
Drug rehabs concentrated on trauma-informed care supply indispensable support for many people! drug rehab recreateohio.com
Detoxing is just the initial step; continuous assistance is necessary after drug rehab. drug rehab recreateohio.com
Эта медицинская заметка содержит сжатую информацию о новых находках и методах в области здравоохранения. Мы предлагаем читателям свежие данные о заболеваниях, профилактике и лечении. Наша цель — быстро и доступно донести важную информацию, которая поможет в повседневной жизни и понимании здоровья.
Почему это важно? – [url=https://obuv-modnaya.ru/narkologicheskaya-klinika-v-mariupole-puti-k-vosstanovleniju-i-novoj-zhizni/]детокс24 мариуполь[/url]
I’m researching soil stabilization for class—your geotech notes helped. My summary is on landon tinker portfolio
Great breakdown of options. If you’re comparing locksmith close me providers, embrace cheap key fob programming .
I’m so pleased to see conversations around mental health and drug rehabilitation getting more attention. Tampa
Working from home in San Antonio when our Mold Remediation issue started. Urgent Mold Removal San Antonio sent a technician within the hour to our place near South San Stadium who fixed it properly the first time. Really appreciated the fast response. mold removal services near me
Need a licensed emergency electrician who can arrive within the hour— local electrical companies looks solid.
Understanding levels of care upfront makes such a difference. We stress this in our own checklists on elderly care as well.
I shipped a motorcycle from Arlington last month—crating options were clearer when I compared carriers on Arlington vehicle shipping .
The emphasis on trust and gut feelings after doing all the research is something we agree with and mention frequently on respite care .
As an adult child living in another state, the clarity here helps me talk more confidently with my siblings. We’ve been using assisted living to compare communities and learn what each level of care actually offers.
Classic car owners around Orlando: enclosed transport via Orlando car shipping kept my paint pristine during a rainy week.
Budget watch: Lexington to West Coast lanes fluctuate seasonally—book when demand dips. I track rates using Lexington vehicle shipping .
It’s motivating to see stories of recovery from eating disorders; they give hope to others dealing with comparable issues! Turning Point of Tampa eating disorder treatment
Moving a call center? Ask about re-cabling and punch-down timing; I started the convo at Long distance movers Dacula .
Anyone have recommendations for storage with climate control? Cheap movers Tampa listed several Tampa options.
I appreciate the reminders about staff-to-resident ratios and specialized dementia training. I’m using a checklist now and will add dementia care as one of the resources to review.
лечение алкоголизма последних стадий в спб [url=https://vyvod-iz-zapoya-v-staczionare-sankt-peterburg-31.ru]лечение алкоголизма последних стадий в спб[/url]
For motorcycles leaving Stockton, are soft tie-downs standard? I found prep tips on Stockton car shipping that seem solid.
Remaining informed about addiction research has actually empowered me throughout my alcohol detox journey! # # anyKeyWord ## drug detox Gahanna
Good info on determining a pro. I found out 24/7 locksmith when trying to find a locksmith close me and they had been splendid.
address https://peptidesnova.com
лечение алкоголизма анонимно в воронеже [url=narkologicheskaya-pomoshh-voronezh-13.ru]narkologicheskaya-pomoshh-voronezh-13.ru[/url]
מענה מהיר ושירות מכל הלב. קישור ישיר: משכנתא לגיל השלישי
We used professional carpet cleaning company for eco-friendly carpet cleaning in Houston and loved the non-toxic solution.
Эта статья подробно расскажет о процессе выздоровления, который включает в себя эмоциональную, физическую и психологическую реабилитацию. Мы обсуждаем значимость поддержки и наличие профессиональных программ. Читатели узнают, как строить новую жизнь и не возвращаться к старым привычкам.
Подробнее можно узнать тут – [url=http://www.rusmedserver.ru/profilaktik/Preimushchestva-vyzova-narkologa-na-dom.html]вызов нарколога на дом[/url]
Hydration is essential during detoxing from drugs! Find out about its value at drug detox methods .
My neighbor near Nighthawk Systems recommended Colorado Springs CO Water Damage Restoration Express when I had questions about Water Damage Restoration for my home in Colorado Springs water damage restoration near me