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
}
Moim priorytetem był widoczny wzrost autorytetu domeny poprzez budowę linków, dlatego wybrałem Proboost w Warszawie i to była trafna decyzja. Pozycjonowanie i budowa linków dały realne rezultaty dla portalu. Doradca marketingowy
this [url=https://wiseccleaner.com/]wise memory optimizer free download version[/url]
Appreciate the detailed post. Find more at tubidy mp3 download .
Love the advice on skimming leaves daily! It really makes a difference. Learn more at Swim and Spas Winnipeg Pool Supply Store .
Living here in McKinney, the heat is no joke. My unit has been blowing warm air for two days now and I’m desperate for a reliable fix https://www.mediafire.com/file/e4g6dbblttm33ro/pdf-82149-84973.pdf/file
Commercial build-outs need recurring swaps; I coordinate a schedule via Scottsdale, AZ roll off dumpster rental scottsdale .
It is interesting to see so much capital flowing into the UK self-storage market right now. With many people moving to smaller living spaces, the demand clearly is not going anywhere https://www.mediafire.com/file/al7lm0srw4d4mr6/pdf-22887-72373.pdf/file
Thanks for this helpful post. Getting into an accident is always so stressful, especially when you are trying to remember all these steps while shaken up Home page
I went through a car accident downtown last year, and honestly, the legal process was just as stressful as the crash itself. Finding a firm that actually listens makes a huge difference https://www.mediafire.com/file/02aq3o3fnlsvvxy/pdf-71829-74457.pdf/file
Living in McKinney, the heat is no joke. My unit started blowing warm air yesterday, and it’s been a nightmare trying to find someone reliable https://wiki-aero.win/index.php/Choice_Air_Care:_Do_They_Charge_Extra_for_Emergency_Service%3F
I recently looked into buying engagement for my small business account. The site promised 2500 likes for only $15 and even claimed that no password required. Still, I worry that Instagram will flag my account for fake engagement https://www.scribd.com/document/1049310917/Do-Bought-Instagram-Likes-Get-You-Shadowbanned-or-Flagged-The-Brutal-Truth-203449
В этой статье рассматриваются различные аспекты избавления от зависимости, включая физические и психологические методы. Мы обсудим поддержку, мотивацию и стратегии, которые помогут в процессе выздоровления. Читатели узнают, как преодолеть трудности и двигаться к новой жизни без зависимости.
Ознакомиться с отчётом – [url=https://malyshok-m.ru/article/ekstrennaya-pomoshh-i-podderzhka-pri-alkogolnom-zapoe-rukovodstvo-dlya-blizkih]капельница от запоя[/url]
Useful advice! For more, visit http://bax.kz/redirect?url=https://beauiwzc207.iamarrows.com/pipes-web-site-layout-what-pages-you-actually-required .
It’s interesting to see all this capital flowing into the UK storage market. I’ve definitely noticed more facilities popping up in my local area recently, which makes me wonder if supply is starting to outpace demand in certain towns storage facility marketing strategies
Finding the right lawyer in Phoenix can feel like such a daunting task after an accident https://wiki-neon.win/index.php/What_Did_the_May_25,_2026_Review_Say_About_Legal_Jargon_and_Explanations%3F
This is a really helpful breakdown for anyone driving in Arizona. I think people often forget to document the scene properly https://mega-wiki.win/index.php/Dog_Bite_in_Arizona:_Should_I_Report_It_and_Who_Do_I_Contact%3F
Living here in McKinney, the heat is no joke. My unit has been blowing warm air since yesterday, and I’m really struggling to keep the house cool carrier vs trane hvac mckinney
Anyone moved a piano or large safe in Cumming? I’m considering leading movers Cumming because they have the right equipment and trained crews.
Ask how they handle work near septic systems. There’s a caution list on licensed tree removal .
I recently saw those sites offering 2500 likes for $15, and the “no password required” claim sounds tempting. However, I definitely worry about my account security https://wiki-velo.win/index.php/How_Do_I_Choose_Between_Cheap_Likes_and_Geo-Targeted_Likes%3F
This was highly educational. For more, visit tubidy mp3 free download .
It’s really interesting to see so much capital pouring into the UK self-storage market lately. I’ve noticed a few new facilities popping up near me, but I’m curious about how the competition is affecting occupancy rates in these saturated urban areas https://stephenwgyg797.fotosdefrases.com/what-does-strong-location-really-mean-for-a-self-storage-facility
This was a great article. Check out http://taxibestellung24.de/php/redirect.php?url=https://jaredasyi668.tearosediner.net/regional-search-engine-optimization-vs-national-seo-which-is-right-for-your-profession-service for more.
Thanks for the comprehensive read. Find more at expertos en extranjería .
Dealing with an accident after getting rear-ended on the I-10 was honestly so overwhelming. I wasn’t sure how to even start the process, but I really appreciated that they offer a free consultation virtual appointment lawyer Phoenix
Living here in McKinney, you know how brutal these summers get. My unit has been blowing warm air lately, and I’m nervous it’s finally giving out https://solo.to/kevin.wang03
This is a really helpful breakdown for anyone driving in Arizona. People often forget to take photos of the scene before moving their cars, which is such a simple-yet-vital step to document evidence click here
The staff at my Harrisburg moving company were courteous and careful. movers in Harrisburg
I just read this piece, but I feel skeptical about the risks. I saw a site offering 2500 likes for $15, which sounds tempting for quick growth. However, do these services compromise my account security? I worry about Instagram flagging my profile https://ricardosuniquenews.almoheet-travel.com/getafollower-support-review-is-non-24-7-support-a-dealbreaker
I appreciated this post. Check out http://mb.tickets.wonderworksonline.com/cart.aspx?returnurl=https://emilianoexxc780.huicopper.com/exactly-how-to-rank-for-near-me-searches-in-your-area for more.
Brentwood’s park system is fantastic; master movers brentwood even includes a post-move local guide so you can explore quickly.
I’ve definitely noticed more of these facilities popping up around my area lately. It makes sense given the housing market, but I wonder if the sector is getting a bit crowded modernizing uk storage facilities
I remember when I had to deal with a claim after my accident last year. It’s definitely overwhelming trying to figure out who to call in the Phoenix area. I think the point about having 24/7 phone availability is super important Get more information
This is such a helpful breakdown for anyone driving in Arizona. I always wondered about the specific rules for moving vehicles out of traffic after a minor fender-bender https://www.inkitt.com/jonathan_barker42
Living here in McKinney, you know how brutal these summers get. My AC started blowing warm air just yesterday, and with the triple-digit heat, I’m really stressing overnight hvac service mckinney tx
Этот информативный текст сочетает в себе темы здоровья и зависимости. Мы обсудим, как хронические заболевания могут усугубить зависимости и наоборот, как зависимость может влиять на общее состояние здоровья. Читатели получат представление о комплексном подходе к лечению как физического, так и психического состояния.
Что ещё нужно знать? – [url=https://astroline.net.ru/2026/06/01/biologicheskiy-diskonnekt-pochemu-preryvanie-sistemnogo-sboya-trebuet-izolyatsii-i-apparatnogo-monitoringa/]вывод из запоя в клинике[/url]
קיבלתי ב- ייעוץ משכנתאות סימולציות שמראות את התמונה המלאה שנים קדימה.
I saw a site offering 2500 likes for just $15, and the ad claimed no password required. It sounds tempting for a quick boost, but I worry about losing my account security https://www.demilked.com/author/helenhunt87/
This was beautifully organized. Discover more at tubidy site .
Thanks for the great content. More at https://chancehpjc268.wpsuo.com/how-cleaning-business-can-build-count-on-via-reviews .
Thanks for the thorough analysis. Find more at tubidy site .
It’s fascinating to see so much capital pouring into the UK self-storage market lately. I’ve noticed a few new facilities popping up in my area, which makes me wonder if the industry is reaching a saturation point https://www.protopage.com/megan.price10#Bookmarks
Make sure they provide a clear pruning objective—health, safety, or clearance. Good examples are on residential stump grinding .
I went through a tough car accident last year, and honestly, the legal process felt overwhelming until I started talking to a firm. I really appreciated that they offered virtual appointments, as it saved me a lot of stress while I was recovering at home https://tr.ee/rHUoJP7N0G
This is such a helpful breakdown of the steps to take after a crash here in Arizona accident victim rights arizona
I found this very helpful. For additional info, visit https://martincvty529.trexgame.net/deep-cleansing-vs-regular-cleaning-which-keywords-convert-better .
Pro tip: take door measurements and clear paths before move day. The team from pro movers arlington breezed through our Arlington duplex.
Helpful suggestions! For more, visit http://www.tradeportalofindia.org/CountryProfile/Redirect.aspx?hidCurMenu=divOthers&CountryCode=32&CurrentMenu=IndiaandEU&Redirecturl=https://damienskvi445.raidersfanteamshop.com/case-study-assisting-an-independent-estate-agent-outrank-the-chains .
Your tips on managing cowlicks saved my morning; product from Glendale barbershop hours helps.
I saw a site promising 2500 likes for $15, and the “no password required” claim makes it seem almost legit. Still, I worry about the long-term safety of my account buy likes for instagram posts