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
}
Идентификация продуктов для азартных игр и доступных криптовалютных кошельков, поддерживающих немедленные депозиты, становится проще после того, как вы создадите учетную запись в казино Crypto Play. Игровые автоматы бесплатно в онлайн-казино велора – [url=https://surveyexpress.info/]velora актуальное рабочее зеркало на сегодня[/url]
Но прежде чем крутить на реальные деньги, вы должны сначала создать счет и пройти аутентификацию.
Обновления выходят регулярно, так что приложение работает без зависаний и торможений.
como jugar joker casino online (obralin.Es)
en salto españa
Заявку можно оставить в любое время, специалист быстро сориентирует по дальнейшим действиям.
Подробнее тут – [url=https://vyvod-iz-zapoya-v-lyubercah14.ru/]вывод из запоя капельница[/url]
For art and mirror crating in Waco, I’d go with the specialists at Waco business movers .
dota 2 live odds
My web site; trav bornholm i Dag
Porta potty rentals are not just about convenience; they are about comfort and hygiene too. porta potty rental company is worth reviewing.
Длительное употребление спиртного неизбежно приводит к общей интоксикации, нарушению работы внутренних органов и развитию абстинентного синдрома. В такой ситуации главная задача близких — оперативно помочь зависимому человеку справиться с отравлением и избежать серьезных проблем. Профессиональная капельница от запоя в Москве — это оптимальный способ быстро очистить кровь от токсинов, восстановить водно-электролитный баланс и стабилизировать состояние больного. В отличие от таблетированной терапии, инфузионная капельница оказывает действие значительно быстрее, запуская усиленное выведение продуктов распада этанола. Обращение к опытным специалистам нашей клиники гарантирует не только экстренное снятие острых симптомов, но и всестороннее медицинское лечение с учетом анамнеза, стажа зависимости и наличия хронических заболеваний печени, почек и сердечно-сосудистой системы. Мы используем только сертифицированные препараты, а положительные отзывы клиентов показывают, что такая капельница действительно помогает вернуть человека к трезвой жизни. Наш администратор Юлия готова принять вашу заявку и ответить на любые вопросы о лечении алкоголизма.
Подробнее тут – [url=https://kapelnica-ot-zapoya-v-moskve14-3.ru/]kapelnica-ot-zapoya-na-domu-cena[/url]
Lock points may also be so disturbing! Thank goodness for professional locksmiths in Orlando who can help out in rough instances. Orlando locksmith
If you’ve been involved in a car accident in Seattle, it’s crucial to seek help from a qualified chiropractor. They can provide the necessary care to address any pain or discomfort resulting from the incident Chiropractor Seattle
como funcionan las apuestas Que es stake 30 en apuestas linea
I enjoyed this read. For more, visit PPC management services for Google .
las casas de Favoritos mundial Qatar apuestas amañan partidos
Вывод из запоя в стационаре нужен тогда, когда человек уже не может самостоятельно остановиться, плохо переносит отмену спиртных напитков, не спит несколько суток, испытывает тремор, тревожность, скачки давления, боли в области сердца, нарушения со стороны ЖКТ и нервной системы. В таких случаях домашние меры часто оказываются неэффективной попыткой «перетерпеть», а резкий отказ от алкоголя без медицинского наблюдения может привести к осложнениям, белой горячке, психозам, судорогам, аритмии, инфаркту или инсульту.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-v-statsionare-v-gelendzhike1.ru/]быстрый вывод из запоя в стационаре[/url]
I always recommend businesses plan their move early and work with movers who have experience handling office furniture and equipment. This link may help: trusted local movers Alameda
Быстро собираем первичную информацию, оцениваем риски и предлагаем подходящий вариант обращения.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-v-statsionare-v-gelendzhike3.ru/]вывод из запоя в стационаре в геленджике[/url]
I like how this post highlights the importance of getting crowns fitted properly. More related tips: Dental Crowns Oxnard CA
Very important for owners. I’d mean contacting First Class Roofing while you prefer fast, nontoxic roofing options—research more: First Class Roofing
Outdoor event planning goes much better when restroom needs are handled professionally. affordable septic pumping can support that process.
Wow that was strange. I just wrote an very long comment but after I clicked submit my comment didn’t appear.
Grrrr… well I’m not writing all that over again. Anyway, just
wanted to say excellent blog!
horse racing best site for esports betting
– https://sscrew.net/,
online
If you’re looking for a fantastic chiropractor in Downtown Seattle, I highly recommend checking out the options available. Many practitioners focus on holistic approaches to wellness and pain management Chiropractor Seattle
Информация об обращении не передается третьим лицам, а детали лечения обсуждаются только с пациентом.
Подробнее – [url=https://vyvod-iz-zapoya-v-statsionare-v-gelendzhike2.ru/]www.domen.ru[/url]
Very nice post. I just stumbled upon your blog and wanted to mention that I have
truly loved browsing your weblog posts. In any
case I will be subscribing in your rss feed and I hope you write again soon!
Thanks for the comprehensive read. Find more at emergency tree removal DeLand FL .
software scommesse
Feel free to surf to my homepage … scommettere Italia austria
Very good write-up. I definitely appreciate this site. Stick with
it!
Thanks for the great information. More at wpływ kawy na zdrowie metabolizm .
EV owners: ask about carrier experience with electric vehicles; I used the checklist from insured auto transport companies Chandler when shipping to Chandler.
apuestas real madrid (Gerard) de la eurocopa
tutorial gambling site (Jon) statistics uk, crush it online casino accept usa and all
canadian bingo springfield mo, or free online pokies win real money united states
301 Moved Permanently [url=https://u-hotel.ru/kak-vybrat-shtory-dlya-gostinoj-sovety-po-tkani-czvetu-i-dline/]More info![/url]
It’s actually very complex in this busy life to listen news on Television, thus I only use internet
for that purpose, and obtain the hottest information.
casas de apuestas fútbol deportivos pronosticos
This was highly educational. More at pensión en Arzúa .
apuestas Las vegas nba ufc
Fantastic post! Discover more at web para mascotas .
Слушайте, кто сейчас хочет получить гражданство Израиля? Замучился я уже самостоятельно собирать архивные бумаги, Сроки записи на архивную проверку горят, нервы уже на пределе до тех пор, не наткнулся на юристов, которые реально помогают на каждом этапе, с гарантией правильного заполнения всех консульских анкет КП. Все архивные документы нам собрали буквально за месяц,
В общем, если не хотите тратить годы на самостоятельные тесты, вся полезная инфа выложена вот здесь консультация по репатриации в израиль [url=https://grazhdanstvo-izrailya-lvy.ru]https://grazhdanstvo-izrailya-lvy.ru[/url] Лучше сразу доверьтесь опытным профессионалам в этой сфере, обязательно перешлите этот пост тому, кто тоже сейчас серьезно думает о репатриации!
This was highly educational. For more, visit alojamiento ideal en España con piscina .
Настольные игры в онлайн-казино для хайроллеровНастольные игры в онлайн-казино для хайроллеров также являются фантастическим вариантом для игроков, которые любят делать крупные ставки. Онлайн казино велора в Украине 2021 – [url=https://1xbet121225.top/]velora зеркало на сегодня[/url]
Общая площадь зоны казино 11000 кв.
В коллекцию казино велора включены:
If you’re looking for a reliable and safe Seattle chiropractor, I highly recommend doing some research on local clinics. It’s important to find someone who prioritizes patient safety and has great reviews from clients Seattle Chiropractor
horse racing southwell results, Donette,
betting sign up bonus
Very informative article. Road debris and temperature shifts make windshield chip fix in Ottawa a common need, so prevention and fast service are most important. Anyone attempting to find extra particulars might also fee dig this .
This post covers important points for apartment moving in Chicago. Elevator reservations, packing, and scheduling are all key details. For more help, visit best Chicago moving company .
Reliable restroom service is one of those details people notice when it goes wrong, so choosing a trusted provider matters. I’d recommend looking into temporary chain link fencing .
This post makes a great point about planning ahead. For businesses in Fresno, choosing the right commercial movers can save time, money, and a lot of stress. Fresno international movers
I always spent my half an hour to read this weblog’s content every day along with a mug of coffee.
We combined two roommates’ loads and split a cheap Mansfield booking from Mansfield residential movers to save more.
Люди, подскажите по личному опыту. То нотариальные переводы документов оформлены неправильно, А кто-то вообще без понятия, с чего правильно начать процесс до тех пор, не наткнулся на юристов, которые реально помогают на каждом этапе, включая детальную подготовку к прохождению собеседования с нативом. Переводы сделали у аккредитованного нотариуса без единой ошибки,
Кому тоже актуально оформить все документы быстро и легально, смотрите сами все условия по ссылке помощь гражданство израиль [url=https://grazhdanstvo-izrailya-lvy.ru]помощь гражданство израиль[/url] Лучше сразу доверьтесь опытным профессионалам в этой сфере, обязательно перешлите этот пост тому, кто тоже сейчас серьезно думает о репатриации!
Tooth pain, cavities, and gum issues can often be avoided with regular dental visits. Helpful info at local general dentists Aurora .
Great tips! For more, visit Restuarant sign repair .