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
}
I never realized how many business phrases come from gambling until I read this! I once used “up the ante” in a meeting, thinking it just meant “raise the stakes,” but my coworkers gave me weird looks—I had confused it with “call the bluff https://ericksimpressivenews.cavandoragh.org/all-bets-are-off-unpacking-the-uncertainty-idiom-in-everyday-business-english
legalne kasyno online free spins bez Depozytu 2026 muchbetter
Very helpful explanation of why professional service matters. furnace heating repair
Totally agree with this! When I was in Thailand, I saw so many people worrying about petty scams but almost no one paying attention to scooter accidents. I witnessed a pretty nasty crash because someone wasn’t wearing a helmet solo backpacker safety advice
I get what you’re saying about RTP not telling the whole story, especially with high volatility games. I once chased a big win on a slot with solid RTP but ended up burning through my budget fast because of long dry spells fantasy sports pricing strategy
I enjoyed this article because it covers the basics many people forget during a move. Creating an inventory list is especially helpful. If allowed, I’d recommend Best Lincoln movers for readers interested in Lincoln movers.
I never realized self-exclusion was even a thing until now. It’s good to know there are tools like that to help keep gambling in check for anyone who might need it. Has anyone here tried setting up a reality check? Wondering how useful they actually are. session limits casino explained
Love how the transfer alerts keep me in the loop even watching from abroad—makes me feel part of the squad no matter where I am https://juliet-wiki.win/index.php/Why_xG_Doesn%27t_Tell_the_Whole_Story
I love how entertainment can bring people together. In my family, our Friday night game sessions have become a special tradition that keeps us connected and laughing digital entertainment
I like that this topic highlights the importance of planning ahead. St. Louis car shippers may have different schedules depending on the season, so early booking can help. Check out St. Louis car shippers for more.
Absolutely agree—Liverpool fans live and breathe every minute of the game now! The way we analyze Salah’s stats shows how much we care, but it’s the matchday atmosphere at Anfield that truly sets us apart https://astro-wiki.win/index.php/Is_Online_Casino_Gaming_Part_of_Football_Fan_Culture_Now%3F
This post is spot on about timing— Baytown long-distance moving company mapped the best Baytown routes to avoid traffic.
I never really thought about how gambling idioms pop up in business lingo until now live metaphor
Totally agree! In our fintech app, adding deliberate pauses during signup actually boosted trust—users felt reassured their info was handled carefully. It’s not about slowing down but guiding users to feel confident https://blogfreely.net/paige-coleman3/how-does-age-verification-work-for-online-casinos
If hand-pulling isn’t cutting it, a targeted post-emergent plan from lawn care could make a huge difference.
I totally get this! When I visited Bali, everyone worried about petty crime but almost no one mentioned the scooters. I saw so many accidents because people weren’t used to how fast and reckless drivers are there https://spencermlsy639.huicopper.com/why-does-the-news-make-travel-seem-scarier-than-it-is
Great insights! Discover more at Carpet Cleaning near me .
I get what you’re saying about RTP being a big factor, but from my experience, volatility plays an even bigger role in how long I stick with a game. I once chased a high RTP slot that paid out super small wins, and honestly, it got boring fast! https://ace-wiki.win/index.php/Why_Does_Interface_Design_Affect_Player_Retention%3F
Totally agree—getting transfer alerts on my phone has changed how I keep up, especially living abroad. Makes me feel connected to the team even from miles away. Still, nothing beats watching a match at the London Stadium with the crowd! Read West Ham
I’ve been playing on MrQ for a while and love how straightforward and reliable it feels knowing it’s fully UK licensed. Makes the whole experience way more chill compared to some sketchier sites out there. https://www.4shared.com/office/MB4qIm9Ajq/pdf-24982-81239.html
I never realized self-exclusion was even a thing until reading this. Definitely makes me think about setting some limits next time I play to keep things fun and safe. Does anyone know how quick the process usually is? https://www.designspiration.com/infourbanextremeyccnd/
I love how this highlights the power of entertainment to bring people together. Our family has a game night every Friday, and it’s amazing how much laughter and connection it creates gambling support services UK
Love how true this is! Liverpool fans live and breathe every stat—like Salah’s goal record this season, it’s insane. The matchday atmosphere at Anfield is electric, nothing compares mo salah stats
Totally agree! In my fintech app, adding a quick verification step upfront actually reduced churn and increased trust. Users felt we cared about security, which made them more comfortable continuing Click here for more
This is a helpful reminder that there are advanced treatment options for pain beyond medication and surgery. Visit: focused shockwave Englewood CO
Staffing in small homes tends to be more stable, which means seniors get help with ADLs from people they actually know and trust. senior care makes a strong case for this continuity.
Totally agree with this! I was so nervous about pickpockets in Rome but didn’t think twice about renting a scooter. Ended up slipping on a wet street and broke my wrist https://unsplash.com/@brett_rodriguez
I always thought “double down” just meant to literally double something, so I was pretty confused the first time I heard it used in a meeting to mean committing more strongly to a risky plan More help
I’ve been playing on MrQ for a while and really love their no wagering requirements on bonuses. Makes cashing out way less stressful! Only downside is their app sometimes lags during big games, but the chat room crew keeps it lively and fun LeoVegas bingo vs Virgin Games
Totally agree—getting those instant transfer alerts has made following West Ham way more exciting, especially living abroad. Nothing beats feeling connected in real-time with other fans even when you’re miles away from London! Have a peek at this website
I’ve tried MrQ a few times and really like how smooth the site is compared to others. It’s good to know they’re fully UK licensed too – makes me feel more secure playing there. https://station-wiki.win/index.php/Fair_Gaming_Standards_Bingo_Sites:_What_You_Really_Need_to_Know
I get what you’re saying about RTP and how it doesn’t tell the whole story, especially with high volatility games https://messiahssuperop-eds.image-perth.org/best-mobile-compatible-online-casinos-a-no-nonsense-guide
Производство блистеров Производство блистеров
Cultivating environments where discussions around psychological health & dependencies take place freely motivates openness within communities!!! ## anyKeyboard #. drug addiction
I love how entertainment can bring people together. Growing up, my family had a weekly movie night that became our special bonding time. It’s amazing how simple shared experiences create such strong connections and memories Learn more here
Love this! Nothing beats the buzz at Anfield on matchday, and Salah’s consistency just keeps us glued to the stats. Watching how every pass and goal affects the standings makes following Liverpool way more exciting nowadays anfield atmosphere
Family-centered addiction treatment can reinforce relationships, and addiction treatment near me makes family participation simpler. addiction treatment
beste live wedden Sport spelletjes sites eu
I never realized self-exclusion was even a thing until I read this. Definitely something I’m going to look more into to help keep my gambling in check. Thanks for sharing! gambling as entertainment budget
Been playing on MrQ for months—love their no-wagering bonus terms, makes cashouts way less stressful. The app had a tiny glitch last week but customer service sorted it out super fast. Plus, the chat rooms are always buzzing with friendly folks Discover more here
I get what you’re saying about RTP being a bit of a rough guide rather than a guarantee. I’ve had slots with high RTP that still didn’t pay out much, while some lower RTP games surprised me with decent wins https://www.mixcloud.com/gary-carter78/
I’ve been playing on MrQ for a while and really appreciate how seriously they take licensing—it makes the whole experience feel way safer and more legit compared to some other sites out there. Plus, their game variety keeps things fresh! https://pastelink.net/6cocy70c
Totally agree! In our fintech app, we added extra verification steps early on, and while it slowed signup a bit, it drastically reduced fraud and support tickets later. Users trusted the process more because it felt secure, not rushed https://www.protopage.com/kevin.grant2#Bookmarks
It’s helpful to see detox discussed in a way that motivates notified decisions. drug detox facility
Totally agree! When I was in Bali, everyone worried about scams or theft, but the real danger was those speedy scooters everywhere. I saw a friend wipe out doing nothing crazy, just crossing the street how base rates affect fear
Я снова здесь. В этом чёртовом зале, пропахшем железом и чужим потом. Мои руки машинально тянут рукоятку тренажёра, мышцы ноют привычной болью, а мысли — мысли совсем не о спорте. Я смотрю на неё. Она сидит за стойкой ресепшена, перебирает бумаги, изредка поднимает глаза и улыбается входящим. Вежливо, дежурно. Но когда наши взгляды пересекаются, в её зрачках вспыхивает что-то совсем иное — тёмное, спрятанное под маской скучающей администраторши. Жена тренера. Катя.
[url=https://spasi-sohrani.com/novosti/item/83101-gemcy-gem-cy-novaya-piramida-vasilenko]смотреть жесткое порно[/url]
Я помню, как увидел её впервые. Год назад, когда только купил абонемент. Сергей, мой тренер, здоровенный мужик с бычьей шеей и вечно красным лицом, орал на меня за неправильную технику приседа. Она подошла, подала ему бутылку воды, мельком глянула на меня — и ушла. Ничего особенного. Обычная женщина, фигуристая, с тяжёлой грудью, которую она прятала под бесформенными футболками, с длинными тёмными волосами. Но было в ней что-то такое… Приручённое. Так дикий зверь, посаженный в клетку, сохраняет грацию движений, но теряет блеск в глазах. Она была красива той красотой, которую уже не замечает муж. Я стал замечать.
Мои тренировки совпадали с её сменами. Я высчитывал дни, когда она будет за стойкой. Сергей, ничего не подозревая, продолжал орать на меня, хлопать по плечу своей лапищей, рассказывать про «базу» и «сушку», а я думал только о том, как она поправляет волосы, как облизывает губы, когда задумывается, как наклоняется над стойкой, открывая взгляду ложбинку груди. Я представлял, какая она там, под одеждой. Представлял её запах. Не дезодорант и духи, а её, настоящий, — той женщины, которая спит с Сергеем, но не любит его. Я был уверен, что не любит. По тому, как она отстранялась, когда он мимоходом хлопал её по заднице. По тому, как она вздрагивала, когда он повышал голос.
[url=https://allll.net/wiki/%D0%A0%D0%BE%D0%BC%D0%B0%D0%BD_%D0%92%D0%B8%D0%BA%D1%82%D0%BE%D1%80%D0%BE%D0%B2%D0%B8%D1%87_%D0%92%D0%B0%D1%81%D0%B8%D0%BB%D0%B5%D0%BD%D0%BA%D0%BE]порно групповое жесток[/url]
Мой член сейчас стоит так же, как тогда, в тот вечер. Я сижу на скамье для жима, а перед глазами — не чёртово железо, а тот момент, когда всё началось.
Это было в пятницу. Сергей уехал на какие-то соревнования в область — то ли судить, то ли выступать, я так и не понял. Зал закрывался рано. Я задержался, доделывал подход, когда услышал её шаги. Она подошла, облокотилась на тренажёр рядом.
[url=https://russian-gate.com/glavnoe/item/302430-gemcy-gem-cy-novaya-piramida-vasilenko-lico-ivan-marchuk]русский анальный секс[/url]
— Ты всегда так долго? — спросила она. Голос был тихий, без обычной дежурной бодрости.
— Только когда есть на что смотреть.
Я сам удивился своей смелости. Она не улыбнулась, не отвела глаза. Просто смотрела на меня так, словно что-то решала. В воздухе между нами повисло напряжение. Я чувствовал запах её тела — она была после душа, но сквозь гель для душа пробивался её собственный аромат.
— Пойдём, — сказала она. — Покажу тебе растяжку. Сергей говорил, у тебя с этим проблемы.
Мы прошли в пустой зал для групповых занятий. Зеркала во всю стену. Маты на полу. Она закрыла дверь на щеколду — просто, буднично, словно делала это сто раз. Я стоял как дурак, не зная, куда девать руки. А она села на мат, развела ноги в шпагат — легко, профессионально, как умеют только гимнастки и танцовщицы. Футболка натянулась на груди, обрисовав соски. Она была без лифчика.
— Ну? — она посмотрела на меня снизу вверх. — Давай. Тянись.
Я опустился рядом. Мои руки дрожали. Я положил ладони ей на плечи, нажал — она подалась вперёд, и её дыхание коснулось моего лица.
— Не так, — прошептала она. — Вот так.
порно жесток
https://www.dr-peprone.ru/121124/novosti-kompaniya-germes/
I think alcohol detox should come with compassion, and alcohol detox near me can offer that locally. alcohol detox
Здорова, народ Отец не встаёт с кровати Жена рыдает Скорая не приедет на такой вызов Короче, врачи стационара реально вытащили — вывод из запоя в стационаре с интенсивной терапией Положили в палату В общем, жмите чтобы сохранить — капельница от запоя в стационаре [url=https://kodirovanie.vyvod-iz-zapoya-v-staczionare-nizhnij-novgorod-xft.ru]капельница от запоя в стационаре[/url] Звоните прямо сейчас Это может спасти жизнь
Totally agree with the idea of building community through fun activities. In my family, we have a weekly game night that brings everyone together, no matter how busy life gets Great post to read
Totally agree on the transfer alerts—getting instant updates really changed how I follow West Ham, especially when I’m abroad. Missed out on so much before https://edward-carr80.raindrop.page/bookmarks-73410183