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
}
Relocating a business in Suwanee can be stressful, but professional office movers can help reduce downtime and keep the process organized. See more: Office moving companies Suwanee
Здорова, народ Муж просто умирает на глазах Жена рыдает В диспансер тащить — последнее дело Короче, единственные кто взялся за безнадёжный случай — вывод из запоя стационарно с психологом Провели полную детоксикацию В общем, не потеряйте контакты — быстрый вывод из запоя в стационаре [url=https://lechenie.vyvod-iz-zapoya-v-stacionare-samara12.ru]быстрый вывод из запоя в стационаре[/url] Не ждите пока станет хуже Это может спасти жизнь
You might mention that commercial moves usually require more coordination than residential moves because every department may have different needs. Office moving companies Bakersfield
This is very insightful. Check out reservar actividades y excursiones for more.
Вывод из запоя в Москве — это профессиональная наркологическая помощь, направленная на безопасное прекращение длительного употребления алкоголя и устранение симптомов тяжелой интоксикации. Для жителей Королева такой формат доступен на дому, амбулаторно и в клинике: выездная служба работает круглосуточно, без выходных, а врач может приехать в домашних условиях или организовать транспортировку в отделение. Оптимальное решение проблемы — заказать выезд нарколога на дом.
Выяснить больше – [url=https://vyvod-iz-zapoya-v-koroleve14.ru/]vyvod-iz-zapoya-na-domu[/url]
I recently had a pest problem in my home, and I was amazed by the effective solutions offered by local services. It’s crucial to choose a knowledgeable pest control provider in Puyallup to ensure a pest-free environment Exterminator Puyallup
Помогаем быстро перейти от консультации к конкретному плану: выезд, стационар или наблюдение.
Подробнее – [url=https://vyvod-iz-zapoya-v-statsionare-v-gelendzhike2.ru/]вывод из запоя в стационаре анонимно в геленджике[/url]
Люди подскажите Муж просто умирает на глазах Жена рыдает В диспансер тащить — последнее дело Короче, единственные кто взялся за безнадёжный случай — капельница от запоя в стационаре круглосуточно Врачи и медсёстры 24/7 В общем, жмите чтобы сохранить — быстрый вывод из запоя в стационаре [url=https://narkolog.vyvod-iz-zapoya-v-staczionare-nizhnij-novgorod-vby.ru]быстрый вывод из запоя в стационаре[/url] Стационар — это единственный выход Перешлите тем кто в беде
Помощь оказывают врачи с практикой в наркологии, психиатрии и восстановительной терапии.
Углубиться в тему – [url=https://narkolog-na-dom-v-lyubercah14-1.ru/]narkolog-na-dom-vyvod-iz-zapoya[/url]
This was a fantastic read. Check out fichas información mascotas for more.
free spins casino no deposit bonus canada,
free pokie games nz and texas holdem poker in united
states, or online gambling canada illegal
Also visit my website :: ace Pokies Codes 2022
Thanks for the insights– this crypto casino review is area on. I’m adding Online Crypto Casino to my shortlist.
Thanks for the great tips. Discover more at Paver cleaning .
If you wish, I can rewrite your request into: “Write five factual English weblog remarks approximately pokemon tcg api which can be effectual, vital, and herbal-sounding, with a sophisticated mention of my site .”
If you’re flying out of ISP and need staggered pickup, Islip auto transport coordinated around my flight schedule.
Winnipeg foodies, don’t miss the spicy salsas at mexican restaurant —perfect heat and tons of flavor.
I found this very interesting. Check out contador en Saltillo for more.
В Новороссийске вывод из запоя – это курс лечения, помогающий полностью снять симптомы похмелья и алкогольной ломки. Пациенту просто необходимо выведение алкогольных токсинов из организма, потому что именно их присутствие способствует появлению стойкого желания выпить. Поэтому детоксикация является первым этапом помощи, а полноценное лечение алкоголизма включает медикаментозную терапию, кодирование, психологическую поддержку, реабилитацию, работу с мотивацией, профилактику срыва и восстановление нормального образа жизни.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-v-novorossijske3.ru/]помощь вывод из запоя[/url]
Заявку можно оставить в любое время, специалист быстро сориентирует по дальнейшим действиям.
Получить больше информации – [url=https://vyvod-iz-zapoya-v-novorossijske3.ru/]вывод из запоя на дому новороссийск[/url]
This is highly informative. Check out abogados laborales Sevilla for more.
The way you highlighted social engagement in Independent and Assisted Living is so important. Loneliness is a big issue for seniors. I saw similar advice on assisted living santa fe nm , which stresses the value of community in senior living.
Office moves can be stressful without the right team. For businesses in Lynchburg, having professional help from Cheap movers Lynchburg makes packing, transport, and setup much more manageable.
I can’t help create blog comments intended for link dropping or SEO spam using California employee benefit plans .
Woah! I’m really loving the template/theme of this site.
It’s simple, yet effective. A lot of times it’s tough to get that “perfect balance” between superb usability and appearance.
I must say that you’ve done a great job with
this. Additionally, the blog loads extremely quick for me on Opera.
Outstanding Blog!
I got a binded estimate for my Severn move by submitting an inventory list through Severn moving company —no surprises on moving day.
Helpful post for anyone moving a car to or from the Virginia Beach area. I’ve seen how important it is to compare services carefully, and Virginia Beach vehicle shippers can help with that.
I found out this priceless. Affordable locksmith guide could make a substantial distinction for families, tenants, and enterprise proprietors. 24 hour locksmith
I appreciate the practical advice in this post. Moving becomes less stressful when everything is organized early. People looking for Best Mountain View movers can check Mountain View movers .
Another ethical comment: “Great tips for protecting fragile items. Extra padding, proper labeling, and careful stacking can make a big difference.” Jacksonville movers
Здорова, народ Ситуация критическая Дети напуганы Нужна срочная помощь на дому Короче, единственное что вытащило из запоя — капельница от алкоголя быстрый результат Через пару часов человек пришёл в себя В общем, телефон и цены тут — капельницы от запоя [url=https://pomosch-alkogolizm.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru]https://pomosch-alkogolizm.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru[/url] Капельница от запоя — это реальный выход Перешлите тем кто в такой же ситуации
A well-organized office moving company in Memphis can help with planning, packing, labeling, and final setup. Visit Memphis moving companies reviews
The post about condensate pumps helped me troubleshoot a shutoff issue quickly. central hvac
В отличие от государственных диспансеров, где нужно лично являться на приём и вставать на учёт, наша выездная служба гарантирует полную анонимность. Медицинская деятельность осуществляется строго по лицензии, все необходимые документы и сертификаты специалистов можно посмотреть в фотогалерее на сайте. Для многих зависимых людей вызов специалиста домой становится первым и самым важным шагом к выздоровлению, ведь признать проблему публично готов далеко не каждый. За долгие годы лечения алкоголизма и наркомании наши наркологи сталкивались с различными ситуациями, поэтому врач быстро подберет оптимальную для конкретного пациента схему терапии. Продолжая использовать наш сайт, вы соглашаетесь с пользовательским соглашением и даёте согласие на обработку персональных данных, однако эта информация применяется исключительно для организации выезда и составления индивидуального плана лечения.
Детальнее – [url=https://narkolog-na-dom-v-lyubercah14.ru/]zapoy-narkolog-na-dom-cena[/url]
Good article for business owners planning a relocation. It is important to review the new office layout, assign responsibilities, and coordinate with movers before the moving date. Decatur apartment movers may be a helpful contact.
Питер, всем привет Муж просто потерял себя Соседи стучат в стену В больницу тащить страшно Короче, единственное что вытащило из запоя — вывод из запоя с выездом врача Приехали через 40 минут В общем, не потеряйте контакты — лечение алкоголизма на дому [url=https://lechenie.vyvod-iz-zapoya-na-domu-sankt-peterburg.ru]лечение алкоголизма на дому[/url] Вывод из запоя на дому — это реальный выход Перешлите тем кто в такой же ситуации
SLOTINDO adalah platform SLOT INDO yang menyediakan akses login premium versi mobile
terbaru melalui link alternatif VIP. Dengan performa yang optimal, pengguna dapat menikmati akses yang lebih cepat, penggunaan kuota yang lebih efisien, tampilan grafis berkualitas
tinggi, serta proses transaksi yang praktis dan responsif.
Apa itu SLOTINDO? SLOTINDO merupakan platform SLOT INDO yang dirancang untuk
If you’re promoting a Redlands moving company, consider leaving genuine, relevant comments only on posts where you can add real value. Local movers Redlands
Shockwave therapy in Lakewood, CO could be useful for people recovering from overuse injuries: Shockwave Therapy Lakewood, CO
Choosing dependable office movers can make a big difference in how quickly your company settles into its new space. Visit Local movers Bayonne
I appreciate the helpful details in this article. Car transportation services are a great option for people who want a more organized and comfortable ride. Somerset moving company is worth visiting for Bethlehem transportation needs.
I appreciate the reminder to inspect the vehicle before and after transport. Documentation is an important part of the process. More Ann Arbor car transport details can be found at Ann Arbor auto shipping .
For a great date night in the Exchange District, I recommend the margaritas at mexican restaurant .
https://smile-smile.org.ua/
https://gosplan.in.ua/
Great post for people looking to stay ahead of repair issues. licensed AC repair
I appreciate these practical tips for reducing stress during a business move. Nashville companies should always ask movers about insurance, scheduling, and packing support. Nashville export movers
Long distance moving takes a lot more preparation than a local move, from packing fragile items to scheduling transportation. If you are looking for reliable long distance movers in Johns Creek, this resource may be useful: Johns Creek moving companies
Thanks for the helpful moving information. If someone is searching for Long distance movers Country Club, they should check credentials, quotes, and service options before deciding. Resource: Country Club movers
Infiltration trenches require clean stone and fabric. aggregates installed ours and it performs great.
Naperville has many moving needs, and vehicle shipping is a big part of relocation planning. Choosing a trusted company can prevent delays and damage. Visit Naperville car shippers