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
}
Bắn cá NBET là chuyên mục cung cấp các nội dung xoay quanh trò chơi bắn cá với cách trình bày sinh động, dễ tiếp cận. Nội dung được sắp xếp hợp lý, giúp người dùng dễ dàng tìm hiểu và trải nghiệm trong quá trình sử dụng website. https://nbet12.com/ban-ca-nbet
Капельница действует быстро благодаря тому, что активные вещества вводятся непосредственно в кровь, минуя желудочно-кишечный тракт. Это позволяет быстро уменьшить симптомы, такие как головная боль, тошнота, слабость, а также нормализовать работу печени и почек, которые страдают от длительного употребления алкоголя. В некоторых случаях, если требуется длительное наблюдение, пациент может быть направлен в стационар, и лечение может продолжаться на летний период с более тщательным контролем состояния.
Детальнее – [url=https://kapelnica-ot-zapoya-nizhnij-novgorod-5.ru/]капельница от запоя на дому нижний новгород[/url]
Casino ZBET là chuyên mục cung cấp các nội dung liên quan đến casino trực tuyến với nhiều trò chơi phổ biến. Khi truy cập, người dùng có thể dễ dàng tìm hiểu cách hoạt động và trải nghiệm thông qua các bài viết được trình bày rõ ràng, dễ theo dõi. https://zbet4.com/casino-zbet
Tài xỉu NOHU90 là chuyên mục giới thiệu nội dung liên quan đến trò chơi tài xỉu, với các bài viết được trình bày dễ hiểu, giúp người dùng nhanh chóng nắm bắt thông tin và cách thức hoạt động. https://nohu90sa.com/tai-xiu-nohu90
Xổ số NOHU90 là chuyên mục cung cấp các nội dung liên quan đến hình thức quay số. Các bài viết được sắp xếp rõ ràng, giúp người dùng dễ dàng theo dõi và tìm hiểu thông tin trong quá trình trải nghiệm website. https://nohu90sa.com/xo-so-nohu90
1вин оина Тоҷикистон [url=http://1win20938.help]1вин оина Тоҷикистон[/url]
ZBET là website nội dung được xây dựng xoay quanh nền tảng giải trí trực tuyến, với hệ thống bài viết hiển thị rõ ràng ngay từ trang chủ https://zbet4.com
Подробнее здесь [url=https://sloh66.cc]кракен ссылка зеркало kraken one com[/url]
NOHU90 là website nội dung được xây dựng xoay quanh nền tảng giải trí trực tuyến, với hệ thống bài viết hiển thị rõ ràng ngay từ trang chủ https://nohu90sa.com
Casino NBET cung cấp các nội dung xoay quanh hình thức casino trực tuyến với nhiều trò chơi quen thuộc. Nội dung được xây dựng trực quan, giúp người dùng dễ dàng tìm hiểu và nắm bắt trải nghiệm tổng quan. https://nbet12.com/casino-nbet
Game bài ZBET là chuyên mục tổng hợp các nội dung liên quan đến các trò chơi bài phổ biến. Các bài viết được trình bày dễ hiểu, giúp người dùng nhanh chóng tiếp cận thông tin và khám phá trải nghiệm tổng quan. https://zbet4.com/game-bai-zbet
Thể thao NOHU90 là chuyên mục tập trung vào các nội dung liên quan đến các bộ môn phổ biến và các giải đấu lớn. Khi truy cập, người dùng có thể dễ dàng theo dõi thông tin nhờ cách trình bày rõ ràng và sắp xếp hợp lý. https://nohu90sa.com/the-thao-nohu90
Live Casino NOHU90 cung cấp các nội dung xoay quanh hình thức casino trực tuyến với tính tương tác cao. Nội dung được xây dựng trực quan, giúp người dùng dễ dàng tìm hiểu và nắm bắt trải nghiệm thực tế. https://nohu90sa.com/live-casino-nohu90
Keep towing service helpful in the course of hurricane season for emergency tows around Bay Harbor Islands.
мелбет демо режим слоты [url=www.melbet27495.help]мелбет демо режим слоты[/url]
melbet contrôle parental [url=https://www.melbet57184.help]https://www.melbet57184.help[/url]
Busy season bookings fill fast—reserve through dog walking services early.
mostbet кушода намешавад [url=https://www.mostbet40827.help]mostbet кушода намешавад[/url]
Hydro jetting sounds like the best way to clear heavy buildup in my long sewer run to the street. I’ll be asking Septic Pumping for a hydro jetting estimate.
Great read! If anyone needs quick window screen repair, I’ve had good results using window screen repair in mckinney for fast fixes and fair pricing.
Very good point about long-term follow-up. Staying in touch with a foot and ankle surgeon, even after feeling better, can prevent setbacks. foot and ankle surgeon NJ
I appreciated this article. For more, visit Garage Door Installation services near me .
Thanks for the insights on moving with pets. We’ll be relocating to Fresno next month and need a patient crew. Thinking of reaching out to Fresno full service movers for a custom estimate.
mostbet бонус без депозита правда [url=www.mostbet89276.help]www.mostbet89276.help[/url]
Tải Go88 ngay hôm nay để nhận ưu đãi và trải nghiệm cá cược chất lượng Tải Go88
For any one evaluating sites this week, try out several rooms on xfap live and spot if the vibe suits you.
Loved this post about modern fades! If anyone’s looking for more tips, check out 24 hour barber near me for inspiration.
If your rails discolor, fence repair service vinyl explains how to remove metal rust transfer without scratching.
Great insights! Make sure your Sterling Heights moving company is insured for safety. Sterling Heights apartment movers
I really appreciate your breakdown of the scorecard weights. I always struggle with the 35% weight on domain quality versus the actual content relevance https://www.4shared.com/s/fjJKtFZNnge
Professional movers make such a difference—especially when it’s a reliable Fort Worth moving company! Fort Worth moving companies
I appreciate the breakdown of your workflow, especially the part about the 80-90% dofollow ratio. Many agencies promise high numbers but fail to deliver on quality, so seeing that specific target gives me more confidence in your process how to measure link building roi
Avoid mixing manufacturers if that you can imagine; I picked a regular line after analyzing emergency break service Greensboro .
mostbet бездепозитный бонус [url=http://mostbet89276.help/]http://mostbet89276.help/[/url]
1win натиҷаҳои бозӣ [url=https://1win20938.help]https://1win20938.help[/url]
как играть в aviator мостбет [url=https://mostbet63740.help]https://mostbet63740.help[/url]
That breakdown of the 35/20/20/15/10 scorecard weights really clears up why my previous agency struggled to deliver results. It makes total sense to prioritize domain authority and relevance over sheer volume https://delta-wiki.win/index.php/The_Truth_About_Publisher_Discovery:_Why_Your_Prospecting_Workflow_is_Probably_Broken
When facing legal trouble, having the right representation is crucial. Ikerd Law Firm in Lafayette stands out for their dedication to clients. Visit criminal defense lawyer lafayette for more info.
My crawl space flooded last year from a broken drain line. If I had known about crawl space clean out entry services like what Portable Toilet Rental offers, I could have caught it sooner.
For anyone planning a big move, hiring a professional Erie moving company is worth every penny. Erie apartment movers
Hassle-Free Experience: The entire process was smooth and hassle-free, making it easy for me to enjoy the results without any stress or complications. How to Seal Pavers Tampa Bay Pressure Washing
1win apk насб [url=https://1win20938.help]https://1win20938.help[/url]
I appreciate the breakdown of your pricing tiers. It is helpful to see how the costs scale based on the domain authority of the placements https://kilo-wiki.win/index.php/How_to_Verify_Real_Organic_Traffic:_A_Guide_for_SEO_Professionals
I love the outdoor vibe in Tampa, and these tents look fantastic for events! Bounce Genie Bounce House Rentals
I definitely agree with your breakdown on the scorecard weights. Using the 35/20/20/15/10 system helps remove so much bias when vetting new partners. My team struggled with quality control before we adopted a similar rubric https://cashaiet614.image-perth.org/how-to-vet-a-publisher-for-topical-relevance-and-why-metrics-are-lying-to-you
I appreciate the breakdown of your pricing tiers because it helps me understand where to start with a limited budget. Most agencies make it so difficult to compare costs upfront https://louisxxyd285.wpsuo.com/why-do-some-outreach-vendors-refuse-to-show-prospect-lists
Ребят, салют! На днях наткнулся на обсуждение старых хитов и решил перекачать старую добрую игруху.
Вообще сейчас мало что нормального выходит, а тут как раз нашел актуальный билд с нормальной оптимизацией. Графика до сих пор глаза не режет, играть можно. Круто, что в этой версии полная локализация на месте.
Для тех, кто в теме, подробности и описание взял отсюда: [url=https://mods-menu.com/1461-dolphin-emulator-dolfin-emulyator-mod.html]тут[/url] . Там все четко расписано.
I appreciate your breakdown of the scorecard weights. We recently tried outsourcing our link building, and that 35 percent weight on domain authority really helped us filter out the low-quality sites Go here
I love supporting local businesses, and my experience with a Charlotte moving company was outstanding. Office moving companies Charlotte
This breakdown really clears up how these agencies operate. I am particularly curious about the 80-90% dofollow ratio you mentioned DR 70+ links