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
}
Fine way of describing, and good paragraph to take information concerning my presentation focus, which i am
going to deliver in college.
Outdoor lighting looks amazing now that residential lighting installer Fort Worth added photocells and low-voltage transformers.
This was a great article. Check out dietas personalizadas for more.
Great insights! Discover more at tornillería y fijaciones .
Marvelous, what a webpage it is! This website gives useful facts to us, keep it up.
Gates of Olympus Xmas 1000
1win официальный сайт скачать [url=https://www.1win72951.help]https://www.1win72951.help[/url]
ปรึกษาปัญหาหน้ามัน-สิวฮอร์โมน ทองหล่อคลินิกไหนเชี่ยวชาญ ดูรายชื่อใน โปรแกรมฝ้าจาง
1win sloturi online [url=http://1win60823.help/]http://1win60823.help/[/url]
mostbet plinko на деньги [url=http://mostbet73481.help/]http://mostbet73481.help/[/url]
Your travel advice on blade storage is helpful. I use a mint tin as a blade bank on the road. I documented a few safe DIY blade banks; link only if allowed: stainless razor blades .
อยากทำ PRP หน้าใสแถวทองหล่อ มีใครแนะนำบ้าง เจอข้อมูลรวมไว้ที่ ออฟฟิศซินโดรม
Great breakdown, We’re in the middle of a real estate closing in Saratoga Springs and I highly recommend hire a good real estate attorney. We used Ianniello Anderson PC and they caught issues. Deed discrepancies came up and they resolved everything real estate attorney albany ny
Этот увлекательный информационный материал подарит вам массу новых знаний и ярких эмоций. Мы собрали для вас интересные факты и сведения, которые обогатят ваш опыт. Откройте для себя увлекательный мир информации и насладитесь процессом изучения!
Прочесть заключение эксперта – [url=https://perm-pb.ru/berezhnyj-vyhod-iz-zapoya-kak-vosstanovit-garmoniyu-dushi-i-tela-bez-lishnih-riskov/]вывод из запоя воронеж[/url]
Nicely done! Find more at Garaginization Storage Solutions .
1win вывести баланс на элсом [url=http://1win56183.help]http://1win56183.help[/url]
Hello colleagues, good post and good arguments commented at this place, I am genuinely enjoying by these.
Candy Blitz Bombs
Well done! Find more at Garaginization Inc .
อยากทำ HIFU ยกกระชับแถวทองหล่อ มีโปรดีๆ ที่ไหนบ้างคะ เช็กข้อมูลจาก Pico Laser แล้วน่าสนใจ
This was highly educational. More at Omni Dental Care .
mostbet rotiri gratuite bonus [url=mostbet13829.help]mostbet13829.help[/url]
1вин скачать [url=https://www.1win94317.help]https://www.1win94317.help[/url]
Great section on leak insurance claims; documentation tips at Euless, TX plumber in Euless .
Thanks for the helpful article. More like this at Oxnard Dental Professionals .
Thanks for the helpful advice. Discover more at nutrióloga para diabéticos .
This was a wonderful guide. Check out Garaginization for more.
Helpful suggestions! For more, visit catálogo ferretería .
Этот информационный обзор станет отличным путеводителем по актуальным темам, объединяющим важные факты и мнения экспертов. Мы исследуем ключевые идеи и представляем их в доступной форме для более глубокого понимания. Читайте, чтобы оставаться в курсе событий!
Тыкай сюда — узнаешь много интересного – [url=https://catsway.ru/skrytaya-ugroza-dlya-zdorovya-vashej-koshki/]капельница от запоя цена[/url]
Hello, its nice article regarding media print, we all be aware of media is a great source of facts.
Sugar Rush 1000
Stairway lighting codes improve safety; layout advice at Spicewood electrician reviews .
мостбет правила пополнения [url=http://mostbet73481.help/]http://mostbet73481.help/[/url]
В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
Переходите по ссылке ниже – [url=https://life-sovet.ru/zapoj-u-blizkogo-cheloveka/]капельница от запоя цена[/url]
1win на компьютер [url=http://1win72951.help]http://1win72951.help[/url]
1win lucky jet cote [url=https://1win60823.help/]1win lucky jet cote[/url]
With havin so much content and articles do you ever run into any problems of plagorism or copyright violation? My site has a lot of exclusive content I’ve
either authored myself or outsourced but it appears a lot of it is popping it up all over the
internet without my agreement. Do you know any techniques
to help protect against content from being ripped off? I’d definitely
appreciate it.
I have been surfing online more than three hours today, yet I never found any
interesting article like yours. It’s pretty worth
enough for me. In my opinion, if all webmasters
made good content as you did, the net will be a lot more useful.
I often read your posts while analyzing reliable platforms like
qh88. Keep it up!
|
Hi! Someone in my Facebook group shared this website so I came to check
it out. I’m definitely enjoying the information. It’s as quality as the
service I get at qh88. I’m bookmarking and will be sharing this with my followers who love online entertainment!
Wonderful blog!
|
Woah! I’m really enjoying the template of this website.
It’s simple. It’s difficult to find a balance
between user friendliness and visual appeal, but you’ve
done it. The blog loads extremely fast, just like the qh88go.it.com
mobile app. Exceptional Blog!
|
I simply couldn’t go away your website prior to saying that I really loved the quality of information you provide for
your visitors. I’ll be back often to check new posts.
This is a topic that is close to my heart, similar to how I feel about qh88!
Best wishes!
|
Greetings! Very useful advice within this article!
It’s the little changes that make the biggest changes.
Many thanks for sharing! By the way, for anyone looking for top
gaming, qh88 is certainly the place to be.
I want to to thank you for this wonderful read!! I certainly loved every little bit of it. I have you book marked to check out new stuff you post…
Your generator interlock overview helped. We sourced a proper install via Overland Park, KS licensed electrician in Overland Park .
Friendly neighborhoods and good-planned streets are effortless to uncover for those who browse the progression sections at Huntingdon Pointe .
During our panel upgrade, the crew coordinated with the utility; arranged via panel swap permit requirements .
อยากทำคอร์สหน้าใส 1 เดือนก่อนแต่งงาน ทองหล่อมีแพ็กเกจไหน แนะนำดูที่ เมโสหน้าใส เจ็บไหม
Your panel bonding screw tip was a lifesaver. I verified with diagrams on residential electrician in Richardson .
Anyone dealing with home purchases in NY, make sure to hire an attorney. Title issues can be tricky and you need someone on your side. real estate lawyer glens falls
1win app aviator [url=https://1win5743.help/]1win app aviator[/url]
http://madridpymesenigualdad.es/
El proyecto Madridpymesenigualdad se consolida como una consultora con experiencia con presencia en el tejido empresarial espanol, que ofrece un acompanamiento profesional a quienes buscan resultados, priorizando en la excelencia del servicio. Visita el sitio a traves del enlace.
мостбет приложение [url=http://mostbet73481.help/]http://mostbet73481.help/[/url]
Great insights on hiring qualified electricians—if anyone needs a reliable pro, check out commercial electrician in Garland Garland, TX .
Терапевтический процесс в стационаре строится по принципу последовательного выполнения клинических задач: диагностика, стабилизация, медикаментозная поддержка и подготовка к амбулаторному этапу. При поступлении врач проводит детальный осмотр, собирает анамнез, оценивает неврологический статус и при необходимости назначает лабораторные исследования. На основе полученных данных формируется индивидуальный протокол, учитывающий возраст, длительность интоксикации, наличие сопутствующих патологий и переносимость лекарственных компонентов. Мы применяем только сертифицированные препараты, зарегистрированные в РФ, и строго соблюдаем клинические рекомендации Минздрава, исключая псевдонаучные методики.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-staczionare-sankt-peterburg-20.ru/]вывод из запоя в стационаре анонимно в санкт-петербурге[/url]
Valuable information! Find more at nutrióloga en Saltillo .
Thanks for the helpful advice. Discover more at ferretería Albacete .
Clearly presented. Discover more at sitio web .