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
}
ייעוץ נטול אינטרסים, שקיפות מלאה – ייעוץ להבראה כלכלית .
выведение алкоголизма стационар [url=https://vyvod-iz-zapoya-v-staczionare-sankt-peterburg-30.ru]выведение алкоголизма стационар[/url]
“For anyone still uncertain where to take their Macs for repairs: look no further than the professionals at Mac Repair!” Mac Repair Near Me
The Plumber Feasterville we found on plumber feasterville fixed our Feasterville hose bib vacuum breaker to stop back-siphon.
Anyone worried about insurance during auto transport to Arlington? I verified carrier coverage using Arlington auto transport .
Our Buda to South Austin move came in under budget using these packing hacks and off-peak hours: Austin moving companies .
For condo moves with elevator reservations, Tampa moving companies had a checklist that saved me headaches.
Winter shipping to/from Lexington? Watch for weather delays on I-75 and I-64. Flexible pickup windows helped me a ton. Resource: Lexington vehicle shipping .
If anyone’s moving a vehicle to or from the Central Valley, compare rates from Stockton car shippers at Stockton auto shipping before booking.
My assets were organized efficiently thanks to the skilled lawyers at estate planning attorney .
EV shipping tip: confirm the carrier’s EV handling experience. I found one via Orlando auto transport that knew the right tie-down points.
Yerel öneriler ve güncel kampanyalar için düzenli olarak van eskort i stockholm sayfasını takip ediyorum.
Dealers in Paterson: bulk transport discounts exist if you schedule in advance. We sourced carriers through Paterson auto shipping and filled a truck.
Appreciate the helpful advice. For more, visit loan agency .
В данной статье рассматриваются физиологические и эмоциональные аспекты зависимости. Мы обсудим, как организм реагирует на зависимое поведение, и какие методы помогают восстановить здоровье и внутреннее равновесие.
Читать далее > – [url=https://nogtipro.com/questions/kto-takoj-narkolog-i-chto-on-delaet/]khimki detox24[/url]
Helpful breakdown on dementia care; we organized Alzheimer’s strengthen in San Diego by means of home care 1st Meridian Home Care San Diego .
Great breakdown of treatments. If you’re comparing locksmith close to me functions, incorporate locksmith orlando .
Great article — bookmarked. For emergency lock ameliorations, business locksmith is a accountable locksmith close to me.
Has anyone tried the rail clip upgrade from vinyl fence repair santa ana ca Santa Ana, CA ? Mine feel sturdier in high winds now.
В данной статье рассматриваются физиологические и эмоциональные аспекты зависимости. Мы обсудим, как организм реагирует на зависимое поведение, и какие методы помогают восстановить здоровье и внутреннее равновесие.
Узнайте всю правду – [url=https://demetra-tmn.ru/kapelnitsa-ot-zapoya-v-rybinske/]лечение алкоголизма[/url]
Is Macquarie Park NSW emergency electrician able to do emergency bonding checks after a shock?
I appreciate how Maryland family law lawyer focuses specifically on Maryland divorce law instead of generic advice that doesn’t match our state’s rules.
קיבלנו תמהיל חכם במקום מה שהבנק דחף, וההחזר ירד משמעותית: משכנתא לגיל השלישי
buy diazepam 10mg
В данной публикации мы поговорим о процессе восстановления от зависимости, о том, как вернуть себе нормальную жизнь. Мы обсудим преодоление трудностей, значимость поддержки и наличие программ реабилитации. Читатели смогут узнать о ключевых шагах к успешному восстановлению.
Нажмите, чтобы узнать больше – [url=https://almanacwhf.ru/narkologiya-na-domu-za-i-protiv/]обратиться за наркологической помощью[/url]
I had concerns about acceptable photo ID, and white card training adelaide clarified with a detailed list.
Diyarbakır’da profesyonel ve saygılı bir deneyim için ben hep Diyarbakır escort ajansı üzerinden ilerliyorum.
For the ones balancing paintings and elder care in SD, home care 1st Meridian Home Care San Diego made scheduling versatile homestead care such a lot more easy.
Нашел удобную страницу, где фильмы и сериалы собраны по понятным разделам https://movietut.top/spisok-chastey/universitet-monstrov.html все части университет монстров скачать торрент на русском подборки можно открыть на КиноТут
If you’re on a deadline, confirm guaranteed windows. I got a firm slot via junk removal .
When it’s freezing and you’re stuck outside, time matters. car locksmith had step-by-step actions to stay safe and warm.
For ash trees, ask about EAB management experience. I located EAB resources via tree removal .
В данной статье рассматриваются физиологические и эмоциональные аспекты зависимости. Мы обсудим, как организм реагирует на зависимое поведение, и какие методы помогают восстановить здоровье и внутреннее равновесие.
Подробная информация доступна по запросу – [url=https://pilles.ru/alkogolizm-v-luganske-kak-najti-puti-k-vyzdorovleniyu.html]detox24 в луганске[/url]
Termite mud tubes photos were eye-opening. I read more detection tips at exterminator Orlando, FL .
В этой заметке мы представляем шаги, которые помогут в процессе преодоления зависимостей. Рассматриваются стратегии поддержки и чек-листы для тех, кто хочет сделать первый шаг к выздоровлению. Наша цель — вдохновить читателей на положительные изменения и поддержать их в трудных моментах.
Проверенные методы — узнай сейчас – [url=http://promedonline.net/bolezni/priznaki-peredozirovki-narkotikami]выезд нарколога на дом[/url]
We compared three Water Damage Restoration companies in Colorado Springs for work on our home near Lakeside Church of Christ, and Colorado Springs CO Water Damage Restoration Express stood out with their upfront pricing and honest assessment water damage restoration companies near me
additional hints https://cloudy-host.com/
Genie opener remotes wouldn’t sync— licensed local garage repair Houston reprogrammed them and adjusted force settings in minutes.
Этот информационный материал подробно освещает проблему наркозависимости, ее причины и последствия. Мы предлагаем информацию о методах лечения, профилактики и поддерживающих программах. Цель статьи — повысить осведомленность и продвигать идеи о необходимости борьбы с зависимостями.
Где можно узнать подробнее? – [url=https://www.universalinternetlibrary.ru/content/narkoticheskaya-zavisimost-kak-lechit/]detox24 в ростове на дону[/url]
Heavy lifting fees can add up—ask ahead. The estimate at junk removal companies included everything.
We compared three Emergency Electrician companies in Oklahoma City for work on our home, and Urgent Electrician Oklahoma City stood out with their upfront pricing and honest assessment. They didn’t push unnecessary repairs like the other quotes suggested. electrician near me same day
Good call to verify equipment suitability, especially for tight urban lots. I found tips on assessing gear at tree service .
If your smart lock keeps desyncing, locksmith can update firmware and recalibrate.
My neighbor recommended Sacramento Precision HVAC Repair when I had questions about HVAC Repair for my home in Sacramento. The technician explained everything clearly and the pricing matched exactly what they quoted hvac repair service near me
Practical and advantageous. After looking locksmith near me, I scheduled carrier with 24/7 auto locksmith .
Thanks for this — for risk-free locks and keys, I have faith locksmith orlando when looking locksmith close me.
I used skin rejuvenation facials Las Vegas to figure out which Las Vegas facials are best for combination skin, and the recommendations were spot-on.
הביאו לי הצעות שלא קיבלתי לבד. מומלץ: ייעוץ להבראה כלכלית
North Indianapolis tip: get multiple quotes and ask about installation warranties when replacing windows affordable window replacement Westfield IN
http://commercialiser-evolis.fr/
Le projet Commercialiser Evolis se positionne comme une structure experimentee focalisee sur le public en France, qui propose un accompagnement professionnel a ceux qui recherchent des resultats, en priorisant sur l’excellence du service. Decouvrez davantage sur le site officiel.