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’s helpful to know that Independent Living is often more about convenience—meals, housekeeping, and social activities—rather than nursing care. I first learned that distinction through reading guides on dementia care .
Many people don’t realize that memory care may involve more frequent care plan reviews due to rapid changes. We suggest what families should look for in these reviews on senior care .
Very informative post about tree care. Healthy trees can improve curb appeal, provide shade, and add value to a property. For additional tree service resources, I recommend tree service
Very helpful for local homeowners. Water heater pilot issues, thermostat faults, and sediment buildup are all common reasons for inconsistent hot water. plumber near me
Thanks for the useful suggestions. Discover more at ac repair near me .
Just had a consultation with a Los Angeles builder, and I’m feeling hopeful about my future home project! high-end home builders LA
A smooth move starts with the right team. Local Snellville movers who are punctual, careful, and organized can make relocation much less stressful. Snellville Mover’s
I’ve seen how small assisted living homes create a family atmosphere where caregivers naturally step in to help with meals and hygiene. assisted living seems aligned with that model of care.
Good advice on keeping lawns green and strong. Using the right grass seed for the local climate can make a big difference. More lawn care tips here: weed control company
I agree that proper packing is one of the most important parts of an international move. Skilled Memphis movers can help protect belongings during transit. long distance moving company
Следующая страница [url=https://bett-vodka.com/]вотка бет[/url]
This is a valuable guide for maintaining reliable cooling. central ac repair
Бонус-код 1xBet при регистрации. Компания 1XBET заинтересована в привлечении новых клиентов, поэтому для новых пользователей действует акция в виде стартового вознаграждения, который равен сумме первого депозита, но не превышает 225 000 рублей. Однако при использовании промокод при регистрации 1xbet букмекерская контора добавит процент к приветственного бонуса. Чтобы получить максимальный бонус на первый депозит, игроку нужно: зайти на сайт букмекера, выбрать создание аккаунта через почту, заполнить данные, ввести промокод и подтвердить согласие с правилами. Акционный код букмекера помогает получить ещё больше бонусов. Промокод — это комбинация, которая позволяет активировать уникальный бонус от букмекера. С его помощью можно получить промо-баллы и другие подарки.
The way you broke down “red flags” to watch for was very helpful. I may summarize those on assisted living for quick reference.
Thanks for the useful moving tips. Packing, loading, and transportation can be overwhelming without the right team. For more help with Houston movers, Cheap movers Houston could be a good resource.
hello!,I love your writing so so much! percentage we communicate more approximately your post on AOL?
I require a specialist on this area to unravel my problem.
May be that is you! Looking ahead to peer you.
I by no means knew that guaranteed flags had such dramatic histories! It’s fantastic how they could replicate the occasions they were created in. Explore greater at Ultimate Flags .
ORCA’s erosion control hydroseeding helps meet local regulations on construction sites and public projects. Hydroseeding
Love the focus on enrichment activities and supervised play. If anybody has confidential experiences with local day cares, share them– while I research, I’ll likewise check hiphound for assistance.
I appreciate this discussion about concrete repair because many homeowners overlook early warning signs like uneven surfaces, flaking, and water pooling. Regular inspections can prevent costly repairs later. concrete sidewalk repair nyc
Thanks for covering sump pump maintenance. A failed sump pump during heavy rain can lead to serious basement flooding. plumber near me
ORCA provides detailed watering and maintenance instructions to ensure your lawn stays healthy after seeding. Hydroseeding
I had lingering back pain from a fall, and chiropractic treatments helped me recover fully. Injury chiropractor
Thanks for the useful post. More like this at ac repair near me .
Counter house optimization ideas are a fine addition. Check Phoenix residential remodeling contractor .
We had a dripping shower valve in Feasterville fixed fast by a Plumber Feasterville we found on plumber feasterville .
Great information on keeping indoor temperatures stable. central ac repair
Thanks for sharing these tips; they’re crucial when trying to find trustworthy roofers like residential roof repair
Stormwater tie-ins to sanitary lines cause problems—verify separation. Our inspection via sewer cleaning confirmed it.
ADA compliance was easy using portable restroom rentals ’s minimums per total unit count.
For wet basements, fix exterior grading first. drainage reshaped the yard and added a curtain drain.
The collaborative atmosphere in many small homes makes it easier to include families in care planning. That transparency helped us feel secure. I learned to insist on this from reading assisted living .
The emphasis on trust and gut feelings after doing all the research is something we agree with and mention frequently on memory care home .
If your event has peak breaks, portable toilet supplier suggests a buffer of extra units on standby.
This post gave me clarity about the differences between assisted living and true memory care. I’ll filter my search on senior care to make sure I’m only looking at specialized memory units.
Бонус-код 1xBet при регистрации. Компания 1хБет заинтересована в расширении аудитории, поэтому для новых пользователей действует акция в виде стартового вознаграждения, который равен сумме первого депозита, но не превышает двести двадцать пять тысяч рублей. Однако при использовании промокоды на ставку 1хбет букмекерская контора повысит величину приветственного бонуса. Чтобы получить повышенную сумму на первый депозит, игроку нужно: зайти на сайт букмекера, выбрать регистрацию по e-mail, заполнить данные, ввести промокод и подтвердить согласие с правилами. Код 1xBet помогает получить ещё больше бонусов. Это набор символов, которая позволяет активировать специальное предложение от букмекера. С его помощью можно получить промо-баллы и другие подарки.
If you have a PTO or auxiliary equipment, confirm driveline geometry accounts for added loads; I bring a checklist from custom U bolts to the shop.
For anyone focused on high‑end finishes and details in Woodland Hills, Custom home building Woodland Hills works with good subs for tile, stone, and millwork.
Appreciate the useful tips. For more, visit muscle strength training Slough .
I love how smaller assisted living homes tend to adapt to each resident’s abilities rather than forcing everyone into the same schedule. respite care really seems to focus on individualized ADL support.
Flags could be debatable symbols, representing equally harmony and division relying on the context—it be valued at discussing these nuances! Visit Ultimate Flags for insights!
Your point about trial stays and respite care in some communities is valuable. I learned about short-term trial options through articles on assisted living , which made the idea less intimidating for my dad.
The Plumber Feasterville we found on plumber feasterville fixed our Feasterville hose bib vacuum breaker to stop back-siphon.
Your guidance on evaluating communication from management (emails, calls, updates) is very realistic. We mention that on memory care home as well.
Love that you mentioned involving the senior in the decision. We talk about family communication strategies a lot on assisted living .
Asking about fall prevention programs and equipment is so important. We cover home and facility safety tips on assisted living .
As a newbie canine parent, I’m investigating day care alternatives that prioritize enrichment. This post assisted! I’ll be bookmarking Hiphounds to compare programs near me.
Many historic flags have passed through changes in which means through the years; it’s exciting to peer how perceptions shift across generations—explore this evolution at Ultimate Flags !
A whole-home water audit reduced loading on our system. We booked both audit and pumping through septic installation .
Trench safety matters—shoring and sloping save lives. Our crew at septic systems followed strict protocols.