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
}
Everything is very open with a clear clarification of the
challenges. It was definitely informative.
Your site is very useful. Many thanks for sharing!
my webpage tonight s racing results at wolverhampton [Emely]
pronostico sporting vs porto
Have a look at my website … ios di scommesse italiani – Alberta,
Aurora neighbors: check no-judgment dental care options at Dental clinic Aurora .
Really beloved the analytical angle. For 2-MMC, distinguishing isomers and recognizing commonly used reducing marketers should be difficult devoid of right kind spectra you can try this out
3D bioprinting’s clinical path is clearer now; we summarized regulatory checkpoints to watch: stem cell therapy .
I added under-shelf LED strips; installation steps were clear on reach-in closets Dallas .
Great job! Discover more at derecho penal Coruña .
Appreciate the comprehensive advice. For more, visit servicios contables Saltillo .
Odličan tekst! Pokrenuo si dosta bitnih pitanja za naše tržište. Kod odabira agencije uvek mi je najveći izazov provera realnih rezultata na duže staze chatgpt as a search engine
Hvala na odličnom tekstu! Upravo me muči situacija sa plaćanjem pouzećem, jer je često komplikovano sve ispratiti kroz sistem https://www.mediafire.com/file/pq2kwts7fdtl187/pdf-46030-30113.pdf/file
I really appreciate your take on the Belgrade SEO market. The ‘no lock-in contracts’ policy you mentioned is a huge selling point for me, especially since I’ve been burned by long-term commitments before The original source
Odličan tekst, hvala na savetima. Ja sam trenutno u procesu pokretanja malog šopa, ali me najviše muči fiskalizacija customer returns law serbia 14 days
One suggestion for anybody utilizing CS2 casino sites: constantly check evaluations, test with little deposits, and never ever run the risk of skins or funds you can’t pay for to lose CS2 roulette gambling site
Greetings! Very helpful advice within this post! It’s the little changes that make the most
significant changes. Thanks for sharing!
Odličan tekst koji pokriva ključne tačke pri izboru partnera. Često se fokusiramo samo na tehnikalije, ali retko ko otvoreno govori o održivosti rezultata Click here for info
Hvala na detaljnom tekstu o e-fiskalizaciji. Upravo ovo me mučilo oko porudžbina koje idu pouzećem jer su pravila ponekad prilično konfuzna za nas male prodavce. Sve mi je jasnije nakon vašeg objašnjenja digital receipt laws serbia
Odličan tekst, hvala što ste ovo podelili jer nam je svima potrebna pomoć oko zakonske regulative. Trenutno se dvoumim oko fiskalizacije za manje porudžbine i da li je slanje pouzećem dovoljno sigurno za početak cost of starting web shop serbia
I really appreciate the point you made about “no lock-in contracts.” It is so rare to find that level of transparency these days. I have been burnt by long-term commitments before that didn’t deliver results Additional info
Appreciate the thorough analysis. For more, visit suministros industriales y herramientas .
Odličan tekst, stvarno je teško naći pouzdanu agenciju na domaćem tržištu ovih dana. Sviđa mi se što ste naglasili važnost transparentnosti kod ugovora, pogotovo onaj uslov od 30 dana otkaznog roka koji klijentima daje dosta sigurnosti https://sethssuperthoughts.fotosdefrases.com/najbolja-ai-seo-agencija-sta-da-ocekujem-na-prvom-video-pozivu
Odličan tekst, baš mi je ovo trebalo. Trenutno imam veliku dilemu oko izdavanja fiskalnih računa za online prodaju Click for more info
I really appreciate you highlighting the “no lock-in contracts” policy for these Belgrade agencies. It makes testing out a new partner feel much less risky for a small business like mine https://milossuperchat.cavandoragh.org/title-tags-and-meta-descriptions-what-actually-improves-click-through-rate
Hvala na odličnom tekstu o fiskalizaciji, zaista mi mnogo znači jer je sve prilično komplikovano za nas koji vodimo male radnje. Najviše me buni deo oko saglasnosti za e-račun kod onlajn kupovine https://judahxvdv180.bearsfanteamshop.com/da-li-moram-fiskalni-racun-i-kad-kupac-placa-pouzece-karticom-kod-kurira
Odličan tekst, pokrili ste ključne stvari koje svaki ozbiljan marketar traži. Posebno mi se dopada onaj deo o 80% link survival rate jer znamo koliko je to danas postalo izazovno sa svim tim promenama algoritama https://www.animenewsnetwork.com/bbs/phpBB2/profile.php?mode=viewprofile&u=1201402
Odličan tekst, baš mi je pomogao oko nekih nedoumica. Planiram da pokrenem malu radnju, ali me muči taj deo sa fiskalnim računima pri slanju pouzećem https://myanimelist.net/profile/brandon_cole23
I really appreciate the emphasis on no lock-in contracts. It’s refreshing to see an agency in Belgrade prioritize trust over long-term commitments. I’ve been burned by rigid agreements in the past, so this model feels much safer for smaller businesses https://www.ted.com/profile/edit
Hi, constantly i used to check blog posts here early in the daylight, for the reason that i love to learn more
and more.
Hvala na detaljnom tekstu o fiskalizaciji. Baš me je mučilo kako se pravilno evidentira plaćanje pouzećem jer se često čekalo na potvrdu od kurirske službe Go to this website
Very useful post. For similar content, visit declaración de impuestos Saltillo .
Odličan tekst, stvarno je teško naći pouzdanu agenciju na našem tržištu. Svi nude brza rešenja, ali retko ko priča o realnoj strategiji http://www.video-bookmark.com/user/michelle.rivera04
Mattress Shopping іn Singapore: The Step-by-Step Guide Moѕt
People Ꮤish Tһey Had
For most Singapore homeowners, buying ɑ mattress іs one of the most personal furniture singapore
decisions tһey face. Ƭhe pressure is real — ʏоu test fօr
seconds іn tһe furniture showroom, but live with tһe result fоr years.
Megafurniture’s Somnuz mattresses ɡive yoս a practical way to compare the most popular mattress singapore types ѕide bʏ siԀe in one furniture store.
Singapore’ѕ unique living environment tᥙrns mattress buying into a һigher-stakes
decision tһan many fiгst-time buyers expect. Singapore’ѕ yeаr-round humidity puts extra pressure ᧐n moisture management
іnside any mattress. Dust mites thrive іn this climate, mɑking hypoallergenic materials ɑ real
advantage f᧐r mаny households. Overnight air-conditioning ᥙse alsօ cһanges how
different foams аnd covers behave compared with showroom testing.
Μost mattress singapore options sold іn Singapore fɑll into one of four main construction categories, and understanding tһe real differences helps you choose smarter.
Pocketed spring designs гemain popular beсause еach
coil ᴡorks on іts օwn, reducing partner disturbance
while allowing air tօ circulate freely. Memory foam іѕ loved foг its
hugging feel and motion isolation, tһough traditional versions
ѕometimes retain warmth in Singapore bedrooms.
Latex mattresses stand ߋut for their responsive bounce, superior breathability, аnd built-in resistance t᧐ allergens and mould.
Hybrid mattresses tгy to balance tһe support and breathability of springs ԝith the contouring comfort οf foam or latex.
Megafurniture’ѕ Somnuz collection conveniently represents tһe main construction types mⲟѕt local families ⅽonsider.
Firmness levels аre talked about constantly, but whаt feels firm
to one person ⅽan feel medium or soft to another.
Sіde sleepers usսally do best on medium-soft to medium ѕo the shoulders аnd hips сɑn sink in sⅼightly.
Back sleepers tend tօ prefer medium tⲟ medium-firm fօr goⲟd lumbar support
without flattening the natural curve. Stomach sleepers neеd firmer support ѕo the lower back doesn’t collapse іnto tһe surface.
HDB ɑnd condo bedrooms іn Singapore ɑre typically ѕmaller, making correct sizing essential rather than just chasing tһe biggest option. Ꭲhe tߋp layer of аny mattress singapore plays а bigger role
іn local conditions than mɑny people realise.
Bamboo covers ᥙsed іn ѕome Somnuz models
provide superior breathability аnd һelp reduce musty build-up oveг timе.
Water-repellent finishes on cеrtain Somnuz mattresses аdd practical protection aցainst accidental spills ɑnd hiցh
humidity.
Нere’s hоw the Somnuz mattresses ⅼine up wіtһ reeal household requirements іn Singapore.
For valᥙe-conscious buyers, tһe Somnuz Comfy delivers ɡood independent coil support аt an accessible рrice point.
Thе Somnuz Comforto ɑdds bamboo fabric and latex fοr thⲟse wһo
prioritise breathability ɑnd natural dust-mite resistance.
Households tһat need spill and humidity protection ᥙsually lean tօward tһe Somnuz Comfort
Night model. The toр-tier Somnuz Roman Supreme delivers premium support ɑnd luxury feel for buyers ѡilling
to invest in tthe highest comfort level.
Moost people test mattresses tһe wrong waʏ duгing furniture showroom visits — ɑnd it leads to regret lateг.
Τo get useful feedback, spend at leɑst ten minutеs on each
model in tһe exact position уou normally sleep in. Megafurniture’ѕ flagship furniture store ɑt 134 Joo Seng Road and the Giant Tampines outlet bоth display the full Somnuz range in realistic bedroom
settings, mɑking extended testing mucһ easier.
Confirm delivery timing matches ʏour movе-іn or renovation schedule — this is
one of tһe most common pain рoints for new BTO owners. Check ѡhether ᧐ld mattress
disposal іs included and read the warranty terms carefully — not
аll “10-year warranties” cover the same things.
Ꮤith the right choice, a gοod mattress from a reputable furniture store ⅼike
Megafurniture ᴡill serve you welⅼ for nearly a decade.
Watch fοr gradual signs lіke neԝ baⅽk pain, centre sagging, օr partner
disturbance — tһese ɑre cleɑr signals the mattress
has reached thе end of іts ᥙseful life. Head tⲟ Megafurniture tоday — either tһeir Joo Seng оr Tampines furniture showroom
— аnd discover ᴡhich Somnuz mattress
іs the perfect fit foг your Singapore һome.
My web ρage :: storage bed frame
Diyarbakır’ın sosyal hayatında aile bağları, arkadaş toplantıları ve geleneksel sohbetler büyük yer tutuyor. Bu konularla ilgili daha fazla paylaşım için özel vip escort kullanılabilir.
I really enjoyed this guide to finding an agency in Belgrade. It’s refreshing to see you emphasize the importance of “no lock-in contracts” because many firms try to trap you for a year https://atavi.com/share/xwekqtz1h4j19
Super tekst! Hvala puno na ovim smernicama. Trenutno se borim sa delom oko fiskalnih računa za online prodavnice customer loyalty programs for webshops
Hvala na detaljnom tekstu, ovo nam svima mnogo znači jer je materija poprilično komplikovana. Najviše me muči situacija sa plaćanjem pouzećem, gde kurirska služba preuzima novac, pa mi nije jasno kako da pravilno izdam taj fiskalni račun u realnom vremenu managing returns without fiscal receipt
sisal la dritta scommesse vicino a me
Patient education reduces unrealistic expectations; downloadable consent aids available: hormone replacement therapy .
If you coach juniors, the Joondalup sports-focused first aid via certified CPR course is great.
Örnek güvenli format: “Yerel mekanlar ve şehir atmosferiyle ilgili verdiğiniz bilgiler oldukça açıklayıcı. Diyarbakır üzerine içerik arayanlar için güzel bir kaynak; benzer başlıklar için ofis eskort hizmeti da incelenebilir.”
pronostici scommesse marcatori, Augustus, del giorno
This was a great article. Check out abogado mercantil Coruña for more.
I’m new to fades and this helped a ton—scheduled with a pro through kids barbershop near me .
В этой публикации мы исследуем ключевые аспекты здоровья, включая влияние образа жизни на благополучие. Читатели узнают о важности правильного питания, физической активности и психического здоровья. Мы предоставим практические советы и рекомендации для поддержания здоровья и развития профилактических подходов.
Это стоит прочитать полностью – [url=https://bsb.net.ru/zdorove/3455-sezonnye-riski-i-sposoby-sohraneniya-zdorovya-v-gorodskoy-srede-nizhnego-novgoroda]наркологическая клиника нижний новгород[/url]
Şehir dışından gelenler için konaklama ve buluşma noktaları önerileriniz yerinde. Ben rezervasyon öncesi tüm detayları ofis eskort Diyarbakır üzerinden netleştiriyorum.
Медицинская публикация представляет собой свод актуальных исследований, экспертных мнений и новейших достижений в сфере здравоохранения. Здесь вы найдете информацию о новых методах лечения, прорывных технологиях и их практическом применении. Мы стремимся сделать актуальные медицинские исследования доступными и понятными для широкой аудитории.
Желаете узнать подробности? – [url=https://malyshok-m.ru/article/trezvyj-vzglyad-na-uyut-kak-skrytye-i-yavnye-zavisimosti-vzroslyh-razrushayut-bezopasnost-detej-i-lomayut-ih-budushhee]платный нарколог на дом[/url]
В этой статье мы рассматриваем разрушительное влияние зависимости на жизнь человека. Обсуждаются аспекты, такие как здоровье, отношения и профессиональные достижения. Читатели узнают о необходимости обращения за помощью и о путях к восстановлению.
Смотрите также – [url=https://tonus-studiya.ru/kto-takoj-narkologi-i-kogda-nuzhna-ego-pomoshh/]капельницы от запоя в Курске[/url]
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://slon8.to-slon5.cc]slon7 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://https-slon3.ru]slon9.to[/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://slotn5.cc]slon5.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.
slon2.to
https://kr2at.cc
Neuroregeneration is tough—our overview of combinational approaches (cells + rehab + neurotrophins) may help: Peptide therapy .
Thanks for the detailed guidance. More at albergue low cost Palas de Rei .
Diabetic foot ulcers benefit from combined cell + ECM strategies; quick algorithm here: Peptide therapy .