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 had no idea that the nap direction of baize affects the ball’s roll so much on a billiard table! It makes sense now why professionals are so picky about their equipment. The detail about maintaining humidity between 40-60% was also fascinating Click here!
I never realized the Dec 22 Spanish Christmas draw was such a big event tied to the holiday season. It’s interesting how gambling traditions vary so much around the world https://www.4shared.com/office/jkP4aDxIge/pdf-21642-27049.html
Great article! The distinction between effects and intent in marketing compliance really hits home. I’ve seen firsthand how an ad’s impact can lead to unexpected scrutiny, even when the intent was clear CAP Code compliance checklist
I like seeing more awareness around advanced therapies for chronic pain and injury recovery. Shockwave Therapy Aurora, CO
I appreciate how this post breaks down the wagering requirements so clearly—35x on £50 quickly adds up to £1,750, which really puts things into perspective. The 60-second withdrawals sound like a game-changer too best Evolution tables UK
This article really helped me understand why RTP matters so much when choosing a slot. I never realized that with a 96% RTP, you’d expect to lose about 80p on every £1 spin over time £1 spin expected loss
Great insights on leasing for live-stream studios! From my experience as a landlord, floor loading capacity is often overlooked but crucial, especially when studios bring in heavy camera rigs and lighting setups secure access control leasing
I really enjoyed your take on the card-table scene in “The Hustler.” The way the lighting creates such intense shadows around the players adds so much to the tension awards season casino scenes meaning
Good review! Fast deals and a large choice of video games are exactly what I anticipate from a crypto casino like top bitcoin casinos .
Great insights on live casino engineering! I’m curious about how latency challenges are managed when scaling to large numbers of simultaneous players Evolution live casino platform
Great article! I especially appreciated the section on setting deposit limits to avoid overspending. One thing I’m curious about is how withdrawal rules might affect quick access to winnings Find out more
Thanks for the detailed guide! I recently installed a mini split myself and was surprised how quickly it went once I had everything prepped what size mini split for 1000 sq ft
I found the mention of deposit limits and time-outs during holiday gambling seasons really interesting. It seems like a smart way to help people maintain control, especially when festive excitement can make it easy to overspend Home page
I never realized how much of a difference the nap direction of baize makes on gameplay! It’s fascinating that aligning it correctly can influence ball speed and accuracy https://www.mapleprimes.com/users/madison_walker02
Great article! The emphasis on distinguishing effects versus intent really resonates with me https://www.mapleprimes.com/users/sean_gibson21
I really appreciate the clarity on wagering requirements in this post—seeing how 35x on £50 totals £1,750 really puts things into perspective https://spencermzuh182.bearsfanteamshop.com/mrq-casino-review-is-it-really-no-wagering-on-winnings
I’d like to thank you for the efforts you’ve put in penning
this blog. I really hope to view the same high-grade blog posts from you later on as well.
In fact, your creative writing abilities has encouraged me to get my very
own blog now ;)
Look into my page :: huurwoning Haarlem
I really appreciate how this article broke down the concept of RTP and house edge. It’s eye-opening to realize that with a 96% RTP, you’re expected to lose about 80p on every £1 spin in the long run https://online-wiki.win/index.php/Low_Volatility_vs_High_Volatility_Slots_%E2%80%93_Which_Feels_Better%3F
Great insights on leasing live-stream studio space! From my experience as a landlord, clear height and floor loading capacities are often underestimated but crucial for heavy equipment setups server room cooling for studio
I loved how the article pointed out the use of rack focus in the card scene from “The Sting.” It really keeps your attention shifting between the players and their intense expressions https://unsplash.com/@brettcooper23
This was very beneficial. For more, visit ayuda enfermedades reumáticas .
For construction sites, portable restroom rentals suggests weekly service and the right ratio of units to crew.
This article gave a clear overview of live casino engineering, especially the role of WebSockets in reducing latency. I wonder how adaptive bitrate streaming interacts with latency in fluctuating network conditions https://messiahssuperop-eds.image-perth.org/how-do-live-casino-sites-stop-late-bets-on-roulette
This article really cleared things up for me, especially about setting deposit limits to avoid overspending why choose UK licensed casino
nowe kasyno online nowe gry (Ines) ze zdrapkami
I never realized how much tradition surrounds gambling events like the Spanish Christmas draw on December 22. It’s interesting how these cultural moments bring people together race that stops a nation meaning
I really appreciate how this post highlighted the 35x wagering on a £50 bonus, which can quickly become overwhelming. The idea of no wagering requirements sounds refreshing. Quick 60-second withdrawals and the UKGC regulation also give me peace of mind Have a peek at this website
This article really helped me understand how RTP and volatility work together. I didn’t realize a 96% RTP still means you’d expect to lose about 80p on every £1 spin over time https://marcoiypu757.timeforchangecounselling.com/how-much-do-i-expect-to-lose-at-1-a-spin-for-an-hour
Great article! Just finished installing a mini split myself and it took about 6 hours total—not as bad as I feared. One thing I worried about was kinking the lineset, but taking my time and carefully bending it helped a lot mini split without vacuum pump
We used portable restroom rentals to confirm service truck clearance and turning radius.
spanien deutschland basketball Wetten online
I had no idea how important humidity control is for billiard tables! Keeping it between 40-60% makes so much sense to maintain the baize and wood integrity billiard cushion rebound
This article really hits home on the importance of placement context in UK marketing compliance. In regulated sectors, even a perfectly crafted message can become problematic if it appears in the wrong environment how to check ASA rulings
It’s helpful that you mention regulatory differences in some states between assisted living and memory care. Families can learn more about local rules through resources like respite care .
For anyone unsure about the differences in daily routines—meals, medication help, housekeeping—between each level, I recommend checking schedules and service lists. I saw useful examples on elder care that mirrored what you describe here.
It’s not just about physical help; in a small home, emotional support is built into everyday interactions like meal prep and walks. That’s a huge advantage I’ve seen discussed on assisted living .
This article gave a clear overview of how live casino streaming works. I’m curious about how latency is managed when players join from regions with unstable internet video pipeline vs game state
I appreciate the emphasis on dignity in small senior care homes. Things like unhurried bathing and individualized grooming routines really preserve self-esteem. elder care seems to promote that philosophy.
Great points on leasing for live-stream studios! From my experience as a landlord, having dedicated risers for power and data really makes a difference in keeping setups neat and reliable. Also, having a low noise floor is essential for clean audio secondary office building for studio
Слушайте кто сталкивался Муж просто потерял себя Родственники не знают что делать В больницу тащить страшно Короче, только это реально спасло — выведение из запоя на дому быстро Через пару часов человек пришёл в себя В общем, не потеряйте контакты — выведение из запоя в стационаре спб [url=https://lechenie.vyvod-iz-zapoya-na-domu-sankt-peterburg.ru]выведение из запоя в стационаре спб[/url] Звоните прямо сейчас Перешлите тем кто в такой же ситуации
I found the mention of the Dec 22 Spanish Christmas draw really interesting, especially how it brings people together during the holidays https://www.mapleprimes.com/users/abigail_adams12
After repairs, get a site map for your records. Our contractor from sewer cleaning provided a PDF and hard copy.
I loved the breakdown of the card-table scene in “Casino Royale.” The way they used rack focus to shift attention between the players really ramped up the tension film motif card table
Врач учитывает симптомы, риски, анамнез и семейную ситуацию, чтобы предложить подходящую программу.
Получить больше информации – [url=https://vyvod-iz-zapoya-v-statsionare-v-gelendzhike2.ru/]наркология вывод из запоя в стационаре геленджик[/url]
This article really cleared things up for me! I didn’t realize that with a 96% RTP, the expected loss on a £1 spin could still be around 4p in the long run https://www.animenewsnetwork.com/bbs/phpBB2/profile.php?mode=viewprofile&u=1220367
Thanks for the well-explained tips on budgeting for online gaming https://www.protopage.com/james.anderson02#Bookmarks
I really appreciate how this post broke down the 35x wagering on £50, showing it equals £1,750—that’s a huge difference compared to no wagering offers. The 60-second withdrawals sound amazing too MrQ withdrawal guarantee UK
Anyone researching Greensboro auto shippers should look for clear contracts, proper insurance, and responsive customer service before making a decision. Greensboro car shippers
When shortening or lengthening shafts, insist on post-mod balance; I keep that requirement from drivelines on my work orders.
Great article on live casino engineering. I’m curious about how latency is minimized while maintaining high-quality video streams for players in different regions ultra low latency streaming guide