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
}
Thanks for the helpful advice. Discover more at Power Washing Pros of Massapequa | House & Roof Washing .
Love seeing local craftsmanship highlighted in the LA area. Custom cabinets make such a difference over big-box options. Bookmarking Cabinet Maker Los Angeles for my upcoming bathroom remodel.
I’m currently exploring surrogacy agencies in Riverside and wanted to focus on organizations that are open, legally sound, and supportive. I’ve been relying heavily on the info I found at riverside surrogacy agencies to shape my list of must-ask questions.
The ability to message clinics directly through contact info on regenerative medicine orange county made arranging my Orange County Botox consultation really easy.
We don’t know the local waterways, so a captained boat from holiday light yacht charters newport beach is a must for Newport Beach.
Great job! Find more at abogado laboral Santiago .
Professional, fresh, and sturdy outcomes—First Class Roofing is precisely what owners want. Commercial Roofing First Class,
That’s the type of workmanship I’d desire on my abode. First Class Roofing looks first-rate. First Class Roofing services,
Your mention of disaster recovery and redundancy is critical, especially in California where wildfires and power outages can happen. Cloud-based phone systems like those from Managed Service Provider California often have built-in failover options.
I came across roof replacement in illinois while searching for “commercial roof repair Oswego” and the content looked pretty comprehensive.
This made me realize I should stop procrastinating and actually build the outdoor kitchen I’ve been dreaming of. I’m based in Orange County and plan to request a quote from driveway installers orange county for a custom BBQ island.
This is a great reminder to stay on top of yard maintenance. For professional lawn care near me, check out pest control near me
This article gives practical steps for preventing pests. Keeping yards trimmed and removing standing water can reduce many problems. Here’s a related resource: pest control near me .
Pest control is definitely one of those services where local knowledge matters. Different neighborhoods can have different pest challenges. lawn care near me is a good resource to consider.
This was quite informative. For more, visit reservar albergue Palas de Rei .
Just finished measuring my oddly shaped laundry room in Los Angeles and realized off-the-shelf cabinets won’t fit. I’m reaching out to Kitchen Remodeling Los Angeles to see what custom solutions they can offer.
For cracked tooth fix close Altrincham Interchange, I placed a health facility on Dentists Altrincham .
Seniors often prefer familiar faces supporting them with personal care. A small home makes that possible because staff turnover and rotation are usually lower. I found assisted living while searching for exactly that type of setting.
For older adults who value privacy, small homes can often provide private or semi-private rooms while still delivering close, supportive care. It’s the model that assisted living seems to champion.
Financial planning and understanding what’s included in the monthly fee are so confusing. I’ve been using respite care to line up questions before I talk with facilities.
It’s easier to coordinate with doctors and therapists in a small setting, so care plans for mobility and daily living are actually followed. respite care explains how this coordination benefits residents.
The right facility can make decluttering so much easier storage units
Эта публикация исследует взаимосвязь зависимости и психологии. Мы обсудим, как психологические аспекты влияют на появление зависимостей и процесс выздоровления. Читатели смогут понять важность профессиональной поддержки и применения научных подходов в терапии.
Изучить рекомендации специалистов – [url=https://novikovnn.ru/the_articles/opasnyy-dosug-kak-traditsiya-vypivat-na-ohote-ili-rybalke-pererastaet-v-zavisimost.html]врач для алкоголика[/url]
Consistent lawn maintenance helps prevent bigger problems later. For nearby professional support, pest control near me may be helpful.
Great insights on maintaining energy-efficient homes in the city! In Los Angeles, HVAC performance can really suffer without proper seasonal maintenance—especially during those dry, hot Santa Ana days read this article
This was highly educational. For more, visit Super Clean Machine | Power Washing & Roof Washing .
Anyone interested in Orange County Botox injections should compare at least a few clinics on Orange County Botox Injections before committing.
Finding the best surrogacy agencies in Riverside can feel overwhelming, especially when you’re new to the process. I discovered riverside become a surrogate and it really helped me understand how to choose a reputable and transparent agency.
В этой публикации мы обсуждаем современные методы лечения различных заболеваний. Читатели узнают о новых медикаментах, терапиях и исследованиях, которые активно применяются для лечения. Мы нацелены на то, чтобы предоставить практические знания, которые могут помочь в борьбе с недугами.
Смотри, что ещё есть – [url=https://diabet12.ru/%d0%b1%d0%b5%d0%b7-%d1%80%d1%83%d0%b1%d1%80%d0%b8%d0%ba%d0%b8/saharnyj-diabet-i-alkogol-skrytye-ugrozy-dlya-metabolizma/]лечение от алкогольной зависимости[/url]
Здравствуйте!
Стройте систему управления денежными потоками с учетом инвестиций в маркетинговые проекты и их окупаемости, чтобы всегда иметь достаточно средств для развития, а также чтобы вы могли планировать свои финансовые ресурсы с учетом маркетинговых активностей и обеспечивать стабильный рост компании без кассовых разрывов.
Более подробная информация по ссылке – https://promomi.ru/naklejki-na-dveryah-v-indoor-reklame-prakticheskoe-rukovodstvo-po-ispolzovaniyu-prostranstva-vnutri-pomeshhenij/
Дифференциация бренда, Факт-лист PR, VeChain криптовалюта
Аудиореклама подкасты, [url=https://finance21.ru/1inch-kriptovalyuta-agregator-token-i-zachem-eto-vsyo-nuzhno/]1inch криптовалюта[/url], Нативная реклама интернет
Всего наилучшего и успехов в финансах!
I appreciate that you covered both technical and non-technical decision factors. Decision makers in California often look for a partner, not just a product, which is why providers like Cabling Services Provider California get considered.
Anyone else in Oswego considering a white reflective roof? I read about the benefits for commercial buildings on roof replacement in illinois .
It’s encouraging to see a growing focus on small, home-style assisted living, where the goal is to support independence in everyday tasks for as long as possible. assisted living has great information about this trend.
I love that many small senior homes encourage residents to move around and participate, instead of doing everything for them. That balance of help and independence, highlighted at assisted living , is so important.
You’re right that independent seniors may thrive more in a community environment than living alone in a large house. I came to the same conclusion after reading comparisons on assisted living and talking with other families.
The way you explained levels of care and how needs can increase over time was very useful. I’m checking which communities on elderly care can handle higher care needs without moving again.
Thanks for the valuable insights. More at albergues Palas de Rei .
Great tips about utilities and gas lines for outdoor kitchens. It’s exactly why hiring a dedicated BBQ islands contractor in Orange County is crucial. I’m currently comparing bids, and bbq islands contractor orange county seems very knowledgeable about permits and codes.
I enjoyed this article. Check out abogado inmobiliario Santiago for more.
Публикация охватывает основные направления развития современной медицины. Мы обсудим значимость научных исследований, инноваций в лечении и роли общественного участия в формировании системы здравоохранения.
Ознакомиться с полной информацией – [url=https://podarok-market.ru/kak-pomoch-blizkomu-spravitsya-s-alkogolnoy-zavisimostyu-i-sohranit-otnosheniya/]клиника лечение алкоголизма цены[/url]
My experience with chiropractic treatment from a ##Puyallup Chiropractor## has been life-changing! Chiropractor
This was beautifully organized. Discover more at mantenimiento de ventanas aluminio .
I had no idea it was so easy to get a captain included with the boat until I saw what yacht charters newport beach offers in Newport Beach.
If you were hurt on Kent Kangley Road, a personal injury attorney can help prove how the crash occurred. Injury lawyer Kent
Reading feedback from current customers is always a good step storage units
I’ve had so much trouble finding a cabinet maker in Los Angeles who understands minimalist, European-style cabinets. From what I’ve seen, Cabinet Maker Los Angeles might actually get the look I’m going for.
I’m really enjoying the design and layout of your blog.
It’s a very easy on the eyes which makes it much more enjoyable for me to
come here and visit more often. Did you hire
out a designer to create your theme? Exceptional work!
Moving from Lakewood to another state? I liked that Lakewood auto shippers showed transit windows and real customer reviews.
This is highly informative. Check out reclamaciones e indemnizaciones Santiago for more.
This was nicely structured. Discover more at Teléfono taxi Arzúa .