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
}
The fabulous practices for valley set up were informative. I had woven valleys redone through Hired Guns Roofing services .
Find resources tailored specifically for your state or region using ## comprehensive estate planning attorney near me
Your thoughts on backsplash designs were eye-opening! Can’t wait to implement some in my LA kitchen remodel—check out Cabinet Refacing Los Angeles for more!
I appreciate how vacuum excavation is eco-friendly! Learn more at Sacramento underground utility locating .
The Canoga Park crew we discovered through Canoga Park full service movers wrapped furniture and doorways meticulously.
The flexibility of hosting workshops or brainstorming sessions aboard yachts is amazing; so many choices exist right here in Newport Beach via newport beach charter yacht !
Brazilian waxing has become a regular part of my routine thanks to Facial Treatments Las Vegas !
I appreciate how thorough they are during the whole process; it really shows they care about their clients!! Eyebrow Services Las Vegas
Just got my security system upgraded by a great locksmith from Orange County! Check out access control installation Orange County !
I love that residential ac repair Tampa offers text updates and ETAs for AC repair Tampa visits.
Piese Ford offers a complete range of accesorii auto Ford, including accesorii exterior Ford and accesorii interior Ford designed for style and comfort https://www.piese-ford.ro/
Yard decks can genuinely transform your outdoor area into a relaxing sanctuary. I’ve been thinking of including one to my home, and I found some wonderful resources on deck products and designs at deck builder . Definitely worth a check out!
Этот информативный текст сочетает в себе темы здоровья и зависимости. Мы обсудим, как хронические заболевания могут усугубить зависимости и наоборот, как зависимость может влиять на общее состояние здоровья. Читатели получат представление о комплексном подходе к лечению как физического, так и психического состояния.
Всё, что нужно знать – [url=http://www.medsm.ru/medikamentoznye-sredstva-dlya-vyvoda-iz-zapoya.html]вывод из запоя частный врач[/url]
KU88 là nền tảng giải trí trực tuyến nổi bật với hệ thống sản phẩm đa dạng như cá cược thể thao, casino trực tuyến, slot game, game bài, bắn cá, lô đề và nhiều chuyên mục hướng dẫn hữu ích bbc
If you haven’t explored what makes this method stand out yet Orange County vacuum excavation
188BET là nền tảng cá cược trực tuyến cung cấp nhiều sản phẩm giải trí như thể thao, casino, game bài và xổ số bbc
Glad I chose this establishment over many others; exceptional care received during every brazilian session Teeth Whitening Las Vegas
TX88 là nền tảng giải trí trực tuyến cung cấp nhiều chuyên mục quen thuộc như thể thao, casino, game bài, bắn cá, nổ hũ và xổ số bbc
I blog frequently and I seriously appreciate your content. This great article has truly peaked my interest. I’m going to bookmark your website and keep checking for new information about once per week. I subscribed to your RSS feed too.
在线购买无处方安定片 xxx Pornhub
MAX88 là nền tảng giải trí trực tuyến được xây dựng với hệ sinh thái sản phẩm đa dạng, nổi bật ở các chuyên mục như cá cược thể thao, live casino, slot game, xổ số, bắn cá và nhiều trò chơi hiện đại bbc
ZBET là nền tảng cá cược trực tuyến cung cấp nhiều sản phẩm giải trí như thể thao, casino online, slot game, đá gà, nổ hũ và các trò chơi may rủi bbc
B52 Club là cổng game giải trí trực tuyến cung cấp nhiều sản phẩm nổi bật như game bài, casino online, cá cược thể thao, bắn cá, đá gà, slot nổ hũ và xổ số bbc
The benefits of working with an experienced attorney for your estate plan cannot be overstated. living trust attorney orange county
Just had an amazing experience with a facial treatment from Brazilian Waxing Las Vegas #—highly recommend it!
Your FAQs answered everything. I still cross-checked reviews on local roll off dumpster rental before booking.
Packing services made a huge difference for our Jersey City condo move; we booked a full-pack crew via interstate movers Jersey City .
I’ve read that many municipalities prefer vacuum excavation due to its efficiency and safety—Orange County should lead the way! Explore more at vacuum excavation orange county .
Wow, I didn’t know how complex underground utilities could be until I read this—thanks for sharing! Fresno underground utility locating
This was a wonderful post. Check out derecho laboral for more.
I found peace of mind knowing my estate plan was handled by experts at probate attorney orange county .
I’m definitely going to recommend vacuum excavation to my colleagues in Sacramento—great insights at Sacramento underground utility locating !
http://frontrangemarketeer.com/
A equipa Frontrangemarketeer consolida-se como uma consultora experiente com forte presenca no panorama nacional portugues, que proporciona solucoes personalizadas a quem procura resultados, destacando-se por nos resultados. Saiba mais no site oficial.
WOW just what I was searching for. Came here by searching for internetcasinogame.net
This guide will be a valuable resource as we expand our fleet; I appreciate all your hard work compiling this information!! cheap box truck insurance
Fantastic breakdown of costs involved in remodeling; it’s crucial information for budgeting properly—find budgeting tips at Kitchen Remodeling Los Angeles !
”Just left another delightful appointment here; can’t help but smile knowing how much care goes into every treatment offered.” Brazilian Waxing Las Vegas
If you’re considering a unique venue for your next conference, think about a yacht in Newport Beach! More info available at yacht charters newport beach .
If your Lakewood street is tight, meet at a nearby lot. My dispatcher arranged it seamlessly through commercial vehicle shipping .
“Loving the community vibe when visiting# # any Keyword###—makes all the difference!” Teeth Whitening Las Vegas
My peaceful backyard retreat wouldn’t be complete without the lovely fountain from ### anyKeyWord###. Pond Designers Irvine CA
Love getting my Brazilian wax done at teeth whitening las vegas when I’m in Las Vegas. They are the best!
For anyone dealing with no hot water on the Southside of Jacksonville, try contacting a local pro via Plumbing company Jacksonville .
I was curious if you ever considered changing the structure of
your site? Its very well written; I love what youve got to say.
But maybe you could a little more in the way
of content so people could connect with it better.
Youve got an awful lot of text for only having 1 or 2 pictures.
Maybe you could space it out better?
Success stories using vacuum excavation are becoming common throughout construction sites in Orange County—excited to see this trend grow! More info: Orange County utility locating !
Excited about maintaining smooth skin thanks to regular visits to ## Skincare Services Las Vegas
Scheduling summer moves in North Las Vegas can be tricky due to heat; I booked early through Office moving companies North Las Vegas and got my dates.
Budgeting for our warehouse-to-office transition is tough. Did you find cheap movers in New Haven transparent on quotes and not nickel-and-dime for stairs and elevator carries?
Vacuum excavation is a game changer in Orange County! The precision it offers is unmatched. Check out vacuum excavation orange county for more info!
В этой статье рассматриваются различные аспекты избавления от зависимости, включая физические и психологические методы. Мы обсудим поддержку, мотивацию и стратегии, которые помогут в процессе выздоровления. Читатели узнают, как преодолеть трудности и двигаться к новой жизни без зависимости.
Что ещё нужно знать? – [url=http://www.rantac.ru/kak-proisxodit-reabilitaciya-narkozavisimyx/]Реабилитация наркозависимых[/url]
Thanks for the valuable insights. More at beneficios seguros Easy Go .