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
}
Aw, this was a really good post. Spending some time and actual effort to produce a great article… but what can I say… I procrastinate a lot and don’t seem to get anything done.
在线购买大麻用于XXX成人色情视频
888starz تسجيل الدخول مراهنات [url=https://www.888starz-egypt7.com]888srarz[/url]
Community yard sale first, then local Sydney junk removal took what didn’t sell.
Can’t wait to attempt out a few new recipes with these pinnacle-notch cream chargers you’ve suggested! Home page
The estimate was detailed and the final cost matched it perfectly. Harland Windows and Siding delivers on their promises. Cannot ask for more from a Raleigh window contractor. Window installation Raleigh
Hi there friends, how is all, and what you would like to say on the topic of this paragraph, in my view its really remarkable in support of me.
viagra pills sexual xxx porn pills
«Кракен-зеркала» — это альтернативные адреса сайтов, которые появляются после блокировок или технических сбоев. Пользователи часто ищут такие ссылки для доступа к ресурсу, однако важно помнить о рисках: мошеннические копии могут похищать данные, пароли и криптовалюту. Эксперты по кибербезопасности рекомендуют проверять адреса сайтов и не переходить по сомнительным ссылкам.[url=https://webcamclub.ru/viewtopic.php?f=23&t=11008]kraken зеркало
[/url]
Wondering if anyone has had experience with eco-friendly options from local # # anyKeyword#? roofing professionals Litchfield
The timer recommendations here are spot on. I found affordable install-and-timer packages via tree removal service near me .
July in Myrtle Beach is hot. The air-conditioned venue made the two-and-a-half-hour show completely comfortable. Smart choice for a summer evening in South Carolina. Dinner show myrtle beach
wir wetten app
my website: wettquoten biathlon
Your checklist made me realize my furnace was overdue. seasonal furnace maintenance Charlotte tuned it and it runs smoother.
Loved the reason of step flashing on partitions. I had siding/roof transitions fixed with the aid of licensed roofing company .
Your style is unique in comparison to other folks I’ve read stuff from.
I appreciate you for posting when you have the opportunity, Guess I
will just bookmark this page.
Way cool! Some very valid points! I appreciate you writing this article plus the rest of the website is
really good.
888srarz [url=https://888starz-uz-online.com]888srarz[/url] .
If you’re looking St. Augustine, you’ll swiftly see why citizens state the most effective company for home insurance in and near St. Augustine is Fender Insurance Agency home insurance
Having connections among peers allows these practitioners access invaluable resources needed during tough situations faced regularly! Belleville personal injury lawyer
В практике круглосуточного лечения применяются следующие этапы:
Ознакомиться с деталями – http://
Very good site you have here but I was curious if you knew of
any user discussion forums that cover the same topics talked
about here? I’d really love to be a part of
group where I can get feed-back from other knowledgeable people that share the same interest.
If you have any suggestions, please let me know. Kudos!
Quality service whenever with Pure Energy Electrical Services! They’re most certainly the most effective electrician in St Augustine.
electrician st augustine
Helpful reminders. Garage Door Repair Tucson inspected my wall button wiring and secured it neatly. professional garage door installation
Top rated solution every single time with The Master’s Lawn & Pest! They’re definitely the best lawn care in St Augustine lawn care st augustine
Top tier solution every single time with The Master’s Lawn & Pest! They’re certainly the most effective landscapers in Gainesville. landscaping near me
A helpful article for those researching Rehabilitation Centre in Noida. Rehabilitation Centre in Noida
starz 888 [url=https://888starz-uz-online.com/]starz 888[/url] .
The article is valuable for understanding Nasha Mukti Kendra in Noida. Nasha Mukti Kendra in Noida
First-rate service every time with The Master’s Lawn & Pest! They’re most certainly the very best lawn care in Gainesville. lawn care gainesville fl
Its like you read my mind! You seem to know a lot about this, like you wrote the book in it or something. I think that you can do with some pics to drive the message home a little bit, but instead of that, this is excellent blog. An excellent read. I’ll definitely be back.
在线购买大麻用于XXX成人色情视频
https://doskazaymov.kz/ кредит с просрочками на 6 000 000 тенге после нескольких отказов – Doskazaymov.kz помогает понять реальную нагрузку
العاب 888 [url=http://www.888starz-egyp.com]https://888starz-egyp.com/[/url]
Superb, what a blog it is! This weblog presents useful information to us, keep it up.
شراء تادالافيل عبر الإنترنت لممارسة الجنس الشرجي xxx
If you’re browsing for the “best Sushi Restaurant near me” around St. Augustine, Ginger Bistro is a no brainer! sushi st augustine
Hi outstanding website! Does running a blog like this take a great deal of work? I’ve no understanding of coding however I had been hoping to start my own blog in the near future. Anyway, if you have any ideas or techniques for new blog owners please share. I know this is off subject nevertheless I just needed to ask. Cheers!
在线购买他达拉非片用于肛交XXX色情
An impressive share! I have just forwarded this onto a friend who has been doing a little homework on this. And he actually bought me breakfast due to the fact that I found it for him… lol. So let me reword this…. Thank YOU for the meal!! But yeah, thanks for spending some time to talk about this matter here on your web site.
موقع احتيالي عصابة من المحتالين
8 starz [url=https://www.888starz-uz-online.com]8 starz[/url] .
Admiring the persistence you put into your site and in depth information you present. It’s nice to come across a blog every once in a while that isn’t the same unwanted rehashed material. Great read! I’ve bookmarked your site and I’m including your RSS feeds to my Google account.
موقع احتيالي عصابة من المحتالين
казино 888starz [url=888starz-uz-online.com]казино 888starz[/url] .
Awesome tip about not overfilling roll-offs. I saw the same advice when I checked roll-off dumpster service .
If you’re looking for the “finest Chinese food near me” around St. Augustine, Ginger Bistro is a must do! chinese near me
This was a great article. Check out alta en RFC Saltillo for more.
Can you tell us more about this? I’d love to find out more details.
شراء تادالافيل عبر الإنترنت لممارسة الجنس الشرجي xxx
I’m not sure why but this blog is loading very slow for me. Is anyone else having this issue or is it a problem on my end? I’ll check back later on and see if the problem still exists.
在线购买大麻用于XXX成人色情视频
Hi there I am so thrilled I found your blog, I really found you by error, while I was looking on Google for something else, Nonetheless I am here now and would just like to say many thanks for a remarkable post and a all round enjoyable blog (I also love the theme/design), I don’t have time to read it all at the moment but I have book-marked it and also included your RSS feeds, so when I have time I will be back to read much more, Please do keep up the awesome work.
شراء تادالافيل عبر الإنترنت لممارسة الجنس الشرجي xxx
This is very interesting, You are a very skilled blogger. I have joined your feed and look forward to seeking more of your fantastic post. Also, I’ve shared your website in my social networks!
在线购买无处方安定片 xxx Pornhub
Сразу после вызова нарколог приезжает на дом для проведения первичного осмотра и диагностики. На этом этапе проводится сбор анамнеза, измеряются жизненно важные показатели (пульс, артериальное давление, температура) и определяется степень алкогольной интоксикации. Эти данные являются основой для разработки индивидуального плана лечения.
Разобраться лучше – [url=https://kapelnica-ot-zapoya-tyumen0.ru/]капельницу от запоя в тюмени[/url]
After a renovation, my ducts were dusty. local ac repair service recommended filter changes and a coil inspection in Tampa.
Whats up this is somewhat of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding expertise so I wanted to get guidance from someone with experience. Any help would be greatly appreciated!
viagra pills sexual xxx porn pills
stars888 [url=https://www.888starz-egypt7.com/]لعبة قمار[/url]
https://pod.beautifulmathuncensored.de/people/c90ec900331e013f95dc021877951523