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
}
It is honestly wild how much mobile gaming has taken off lately. I find myself hopping onto a quick game whenever I am commuting on the train. The fast loading times really make a difference when I only have a few minutes to spare Find more information
Nicely done! Discover more at kitchen remodel company .
If you’re switching to induction cooking, solar power companies near me Antioch, CA helps estimate the added solar capacity.
I’ve definitely noticed how much my habits have shifted toward mobile lately streaming apps with best algorithms
Your part on standby losses prompted me to tweak settings I learned about on solar providers .
Drone biosecurity protocols between fields—checklist at precision drone spraying .
Demand-response programs pair well with batteries; enrollment tips at Chico, CA solar panel installers were useful.
That was a really interesting breakdown of how the math behind the games actually works. I honestly never realized how much the UX design influences how we perceive volatility https://www.instapaper.com/read/2020338008
I’ve noticed how much these apps rely on personalization to keep things engaging. It’s definitely a nice touch when the lobby shows games I actually enjoy instead of random clutter Click here to find out more
I agree that casual settings often spark the most creative breakthroughs. It is truly fascinating that 18 Nobel laureates credited their time at the beach for helping them solve complex problems Take a look at the site here
I have a love-hate relationship with these game mechanics. While streaks keep me consistent in apps like Duolingo, I honestly feel like these badges often manipulate my screen time rather than helping me learn https://www.hometalk.com/member/248852335/ola1290160
I’d love suggestions regarding suitable protective coatings once projects have been completed successfully! commerical carpet tiles
Nice callout on production monitoring; my dashboard from a company on Pleasanton, CA solar power companies near me is addicting.
I really appreciate this post. I have struggled with overspending on entertainment for a long time, but setting a fixed monthly fun limit has been a total game-changer for me cancelling unused digital services
Appreciate the helpful advice. For more, visit payday loans near me .
I am so excited to see bingo making such a big comeback! Honestly, I’ve been looking for something low-stress to do while winding down at night once the kids are finally in bed Find more information
I really enjoyed reading your take on live dealer games. For me, the best part is definitely the trust factor get more info
Your advice on flat roofs was enlightening! It’s great to know there are effective solutions for drainage issues. complete roof replacement
I really appreciate how much these apps have changed my daily routine. The delivery tracking feature is honestly my favorite part because it takes the guessing game out of waiting for packages https://www.pexels.com/@genevieve-dunn-2162330144/
Lightning and surge protection matter; solar installers grass valley Grass Valley, CA includes SPD options in quotes.
It is wild how gaming terms dominate our daily chats now. I actually saw a coworker use GG after we finally finished a long project last week. It really shows how much gaming culture impacts the way we communicate online today https://www.instapaper.com/read/2020335100
Great insights on commercial rooftops—portfolio managers can consult Concord solar installation services .
Battery sizing confused me until I checked a guide at Rocklin, CA solar installers near me .
Great to see discussion on bifacial panels; specs compared at Concord, CA solar power companies near me .
The photography makes the dishes look irresistible; I browse more at latin food spring tx Zera’s Latin Food for plating ideas.
HOA approvals can be tricky; Sacramento, CA solar installation companies near me shares templates and best practices to get approvals fast.
I found this very helpful. For additional info, visit Pressure washing near me .
I have definitely noticed this shift too. Honestly, I used to be a console-only player, but now I find myself squeezing in mobile games whenever I am commuting to work secure transactions for gaming apps
If you’re dealing with a rat infestation, it’s crucial to address it quickly to prevent health risks and property damage. Effective rat removal techniques can make a significant difference in maintaining a safe and clean environment Puyallup Carpet Beetle Treatment
Your note about temperature and ventilation during painting is practical. Our pro from drywall repair denver brought fans and monitored conditions to ensure proper curing after drywall repair.
If you’re considering filing a claim, speaking with an injury lawyer can clarify your options and rights! Start your journey at Wasilla Dog Bite Lawyer .
Performance ratio benchmarks help— Stockton, CA solar panel installation tracks PR in the monitoring portal.
I’ve definitely noticed this shift with how I use Spotify. The mobile-first approach makes the personalization algorithms feel so much more intuitive when I am on the go http://www.video-bookmark.com/user/aaron.henderson00
I’ve been researching options for depression treatment in Newport Beach and came across Depression Treatment Newport Beach . The approach they describe sounds promising, especially the combination of therapy and lifestyle support.
I enjoyed this article. Check out residential pressure washing Bayport for more.
В этом обзоре представлены различные методы избавления от зависимости, включая терапевтические и психологические подходы. Мы сравниваем их эффективность и предоставляем рекомендации для тех, кто хочет вернуться к трезвой жизни. Читатели смогут найти информацию о реабилитационных центрах и поддерживающих группах.
Узнать больше > – [url=https://zlatgb174.ru/kapelnica-ot-pohmelya-v-irkutske-bystroe-vosstanovlenie-v-klinike-klinika-plyus.html]кодирование от алкоголизма в Иркутске[/url]
This was a super insightful breakdown of how these games actually work behind the scenes. I never really paid much attention to volatility before, but it makes so much more sense now. I’ve started setting strict deposit limits lately to keep things fun https://www.livebinders.com/b/3714409?tabid=c124380d-6e8c-3e30-26f5-0203c0662fc0
Claim history is something many of us ignore until it bites us. I had two small claims last year and my premium jumped Cheap Box Truck Insurance
I really appreciate how much faster these mobile-first apps feel compared to the older desktop versions I used to play. The fast loading speeds make a huge difference when I only have a few minutes to play during my commute https://atavi.com/share/xw8ul4z16f5t3
I use Duolingo and I know those streaks are addictive. Sometimes it feels like they are just manipulating my time rather than helping me learn https://www.protopage.com/ryan.stark2#Bookmarks
I agree that shoreline preservation needs more focus. Reading about the 1962 study really shifted my perspective on how coastal erosion patterns impact local wildlife habitats More help
This was very enlightening. For more, visit หวยออนไลน์มาแรง .
I really enjoyed reading this perspective on managing entertainment spending. Setting a fixed monthly fun limit has been a total game-changer for my bank account. It really helps me stay on track without feeling like I am missing out on life https://www.livebinders.com/b/3714415?tabid=9d557015-c154-3c11-d461-c0f1afcbb763
I totally agree with your points about the transparency of live dealer games Browse this site
Why users still make use of to read news papers when in this technological
globe all is existing on web?
I have noticed how much easier life feels now that I use a mobile wallet for almost every purchase. It has completely changed my daily routine since I rarely carry a physical card or cash anymore website
Gaming terms influence our daily communication more than ever. I actually saw a coworker type “GG” at the end of a long email thread last week. The casual tone surprised me since we work in a strict finance office livestream memes
Appreciate the thorough write-up. Find more at asesores contables Saltillo .
Great list of must-have skills for medical aesthetics. I’m ticking them off with advanced aesthetics resources.
For families concerned about memory issues, your clarification around which environments can handle mild versus advanced dementia is crucial. I dug into more specialized memory care information on respite care when planning for my uncle.