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
}
Family members interaction is vital. The care team we discovered through memory care gives regular updates and satisfaction.
1win aviator демо [url=1win59801.help]1win59801.help[/url]
From the initial consultation, Salt Lake Injury Law builds a thorough strategy tailored to your injury case. Car accident lawyer
The crawl space tips are on point. I combined them with sealing steps from pest control contractor reviews .
DA88 được xây dựng như một nền tảng nội dung có cấu trúc rõ ràng với các chuyên mục tiêu biểu như bắn cá, casino, đá gà và nổ hũ, giúp người truy cập dễ dàng định vị và tiếp cận đúng nhu cầu ngay từ đầu bbc
KU88 được xây dựng như một nền tảng nội dung có cấu trúc rõ ràng với các chuyên mục tiêu biểu như casino, lô đề, slots và thể thao, giúp người truy cập dễ dàng định vị và lựa chọn đúng nội dung mình quan tâm bbc
VU88 được xây dựng như một nền tảng nội dung có cấu trúc rõ ràng với các chuyên mục tiêu biểu như bắn cá, casino, đá gà và esports, giúp người truy cập dễ dàng định vị và lựa chọn đúng nội dung mình quan tâm bbc
VUA88 được xây dựng như một nền tảng nội dung có cấu trúc rõ ràng với các chuyên mục nổi bật như thể thao, casino, bắn cá và đá gà, giúp người truy cập dễ dàng định vị và lựa chọn đúng nội dung mình quan tâm bbc
Here’s the latest
• Talks to end war: Trump administration officials are working to arrange a meeting in Pakistan this weekend to discuss an off-ramp to the war, two senior administration officials tell CNN. Iran has taunted the White House by suggesting it may be negotiating with itself. It is still unclear whether Tehran has agreed to any of the terms in a 15-point proposal from the US that sources said was shared with Iran via Pakistan.
[url=https://slon10ato.cc]slon10.cc[/url]
• US troop deployment: Around 1,000 US soldiers with the Army’s 82nd Airborne Division are preparing to deploy in coming days to the Middle East, sources told CNN.
[url=https://kraab5-ccc.ru]slon7 cc[/url]
• Strikes persist: A residential area in Tehran was hit by an airstrike, according to the Iranian Red Crescent said. Drones struck a fuel tank at Kuwait International Airport, the country’s civil aviation authority said.
[url=https://slon2ato.cc]slon10 to[/url]
• Strait of Hormuz: Multiple vessels have passed through the strait since yesterday morning, tracking data appears to show, as Iran says it will charge countries a fee for safe passage through the critical waterway.
slon3 to
https://krab5.net.ru
If you’re in retail and you’re trying to sell something nobody
[url=https://kraken-site.shop]kraken ссылка tor[/url]
wants to buy anymore, like electric typewriters or video tapes, you’re in a world of hurt,”
[url=https://kraken7jmgt7yhhe2c4iyilthnhcugfylcztsdhh7otrr6jgdw667pqdonion.org]кракен даркнет тор[/url]
said Cohen, who blames Lampert for the store’s current state.
[url=https://kraken2trfqodidvlh4aa337cpzfrhdlfldhve5nf7njhumwr7.com]кракен даркнет через тор[/url]
“But customers didn’t stop buying circular saws or screwdrivers and hammers or appliances.
If you’re in retail and you sell things people want to buy, your success or failure is entirely
based upon what kind of skill you bring to the table.
He had none.
кракен маркет только через тор
https://kraken-cc.com
Right here is the right site for anybody who really wants to find out about this topic. You know a whole lot its almost hard to argue with you (not that I personally would want to…HaHa). You certainly put a brand new spin on a topic that has been written about for ages. Excellent stuff, just excellent!
new online casino slot games
VK88 được xây dựng như một nền tảng nội dung có cấu trúc rõ ràng với các chuyên mục nổi bật như casino, bắn cá, nổ hũ và thể thao, giúp người truy cập dễ dàng định vị và lựa chọn đúng nội dung mình quan tâm bbc
11WIN được xây dựng như một nền tảng nội dung có cấu trúc rõ ràng và dễ tiếp cận, giúp người truy cập nhanh chóng xác định đúng khu vực mình quan tâm bbc
1win телеграм дастгирӣ [url=http://1win26514.help]1win телеграм дастгирӣ[/url]
Pet therapy and intergenerational programs add real joy to daily life. memory care
Misaligned tracks were chewing up my rollers; garage door spring repair corrected the alignment and reinforced brackets.
This was a wonderful guide. Check out respite care for more.
ใครอยากจองออเดอร์ล่วงหน้า แนะนำช่องทางที่ ร้าน ข้าวมันไก่ ใกล้ฉัน ของผู้กำกับสับไก่ข้าวมันไก่ธนาพล
pin-up yeni slotlar [url=https://pinup2010.help]https://pinup2010.help[/url]
This is a solid overview of how crucial proper legal representation is in criminal cases! criminal defense attorney
Postpartum integrative support in Culver City is easy to find on Integrative Medicine .
Love exactly how you broke down ISO/IEC calibration requirements for California facilities. For a trusted companion, describe calibration company california .
“An empathetic ### anyKeyWord ### truly makes navigating post-accident complexities easier.” Car Accident Attorney
Appreciate the lifelike suggestions — massachusetts seo company equipped clear local optimization priorities.
obviously like your website but you have to check the spelling on quite
a few of your posts. Several of them are rife with spelling issues and I
find it very bothersome to tell the reality however I’ll certainly come back again.
I didn’t realize the importance of having legal representation until I faced a car accident in Anchorage. Don’t wait—contact someone through Injury attorney .
”Never hesitate pursuing justice following unfortunate incidents—it’s within rights & responsibilities under law!” Bus Accident Lawyer
I’ve recently had a huge problem with pests in my home, and I didn’t know where to turn exterminators near me
I recently visited a ##Puyallup Chiropractor## and it made such a difference in my back pain! Highly recommend checking one out! Puyallup Chiropractor
Для оценки состояния используется расширенная диагностика: лабораторные анализы, ЭКГ, психологическое тестирование и биохимические маркеры. По результатам обследования составляется индивидуальный план, включающий детоксикацию, фармакотерапию и реабилитационные мероприятия. Ниже представлена таблица, описывающая структуру этапов лечения.
Детальнее – [url=https://narcologicheskaya-clinika-v-rnd19.ru/]наркологическая клиника стационар ростов-на-дону[/url]
mostbet вход в аккаунт [url=http://mostbet15384.help]http://mostbet15384.help[/url]
A dedicated car accident lawyer will fight tirelessly for your rights and ensure that you receive every penny you’re entitled to after an accident.
mostbet plinko tips [url=www.mostbet94827.help]mostbet plinko tips[/url]
1вин официальный сайт вход [url=http://1win59801.help]http://1win59801.help[/url]
I relish, result in I found just what I used to be taking a look for. You’ve ended my 4 day lengthy hunt! God Bless you man. Have a nice day. Bye
best real money online casino slots
Этот текст посвящён сложным аспектам зависимости и её влиянию на жизнь человека. Мы обсудим психологические, физические и социальные последствия зависимого поведения, а также важность своевременного обращения за помощью.
Запросить дополнительные данные – [url=https://zagar-ok.ru/zdoroviy-zagar/pochemu-glubokaya-intoksikaciya-meshaet-idealnomu-zagaru]нарколог стационар спб[/url]
Excellent explanation of mobilephone-first layout; I compiled styles that paintings properly on small screens at digital marketing northampton ma
Love the point about personalization of care plans. elderly care explains levels of care in plain language.
This was quite informative. More at memory care .
I’d like to find out more? I’d love to find out some additional information.
new online casino slot games
This post highlights exactly what households stress over: count on and openness. We discovered clear answers with respite care when selecting assisted living.
1win адрес офиса [url=http://1win68503.help/]http://1win68503.help/[/url]
It’s encouraging to see programs that engage residents’ senses and memories. senior care
This post reminded me to review contracts carefully. respite care has tips on red flags and what to negotiate.
FABET được xây dựng như một nền tảng nội dung có cấu trúc rõ ràng với các chuyên mục nổi bật như bắn cá, casino, đá gà và game bài, giúp người truy cập dễ dàng định vị và lựa chọn đúng nội dung mình quan tâm bbc
Why visitors still make use of to read news papers when in this technological world all is accessible on net?
new online slots casino
Этот информативный текст сочетает в себе темы здоровья и зависимости. Мы обсудим, как хронические заболевания могут усугубить зависимости и наоборот, как зависимость может влиять на общее состояние здоровья. Читатели получат представление о комплексном подходе к лечению как физического, так и психического состояния.
Углубиться в тему – [url=https://dizzwizz.ru/psihika/psihoterapiya-pri-zavisimostyah-specifika.html]наркологическая помощь стационар[/url]
Hello, after reading this amazing paragraph i am too delighted to share my familiarity here with friends.
new online casino slot games
For hottest news you have to visit world wide web and on world-wide-web I found this site as a most excellent web site for latest updates.
new online casino slots
Терапевтический процесс в стационаре строится по принципу последовательного выполнения клинических задач: диагностика, стабилизация, медикаментозная поддержка и подготовка к амбулаторному этапу. При поступлении врач проводит детальный осмотр, собирает анамнез, оценивает неврологический статус и при необходимости назначает лабораторные исследования. На основе полученных данных формируется индивидуальный протокол, учитывающий возраст, длительность интоксикации, наличие сопутствующих патологий и переносимость лекарственных компонентов. Мы применяем только сертифицированные препараты, зарегистрированные в РФ, и строго соблюдаем клинические рекомендации Минздрава, исключая псевдонаучные методики. Стандарты оказания медицинской помощи фиксируются во внутренних регламентах и регулярно проверяются независимыми аудиторами.
Подробнее – [url=https://vyvod-iz-zapoya-v-staczionare-sankt-peterburg-17.ru/]нарколог вывод из запоя в стационаре в санкт-петербурге[/url]