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
}
Appreciate the detailed insights. For more, visit The Glam House TN .
GEM88 tự hào là nhà cái uy tín số 1 Châu Á, cung cấp sảnh Thể thao rực lửa, Casino trực tuyến thực tế, Nổ hũ đổi thưởng và Bắn cá 3D đỉnh cao tại GEM88 Care. gem88
I was barely sleeping due to sciatic pain. Premier Chiropractic’s approach gave me my life back. Car accident chirorpractor Tacoma
I liked your note on preserving CCTV footage early. car accident lawyer provides an evidence preservation letter.
This is a timely reminder. I have seen too many clients get caught out by the 21-day rule. It is so easy to let the notice sit on a desk, but that clock starts ticking the moment it is issued https://uniform-wiki.win/index.php/The_DPN_Trap:_Why_Your_Mailroom_Isn%27t_Your_Calendar
I finally ordered one of these jacquard suits after seeing them everywhere. The fabric quality is decent for the price, though the colors look a bit different in person than on the site. I am glad they offer a 7 days exchange policy just in case https://pixabay.com/users/55458212/
Thanks for the informative content. More at MMD Medical Practice .
I honestly had no idea the firm managed to secure a $6.15M result for that case. It is wild to see how much work goes into these settlements behind the scenes in North Texas wrongful death lawyer Dallas
Gap insurance saved me after a total loss. I found that tip at Car Accident Attorney .
GEM88 tự hào là nhà cái uy tín số 1 Châu Á, cung cấp sảnh Thể thao rực lửa, Casino trực tuyến thực tế, Nổ hũ đổi thưởng và Bắn cá 3D đỉnh cao tại GEM88 Care. gem88
1win app for iphone [url=https://1win54316.help]https://1win54316.help[/url]
For fragile items, double boxing works. The packers I hired through storage services handled all dishware flawlessly.
В Санкт-Петербурге услуга срочного вывода из запоя на дому востребована в ситуациях, когда состояние пациента ухудшается и требуется немедленная помощь. Врач проводит консультацию, оценивает общее состояние, длительность запоя и выраженность симптомов, после чего определяет тактику лечения при алкоголизме. При необходимости помощь оказывается в кратчайшие сроки, без ожидания госпитализации в стационаре. Услугу можно заказать заранее или срочно через сайт клиники.
Исследовать вопрос подробнее – http://vyvod-iz-zapoya-na-domu-sankt-peterburg-10.ru/
Managing online reputation feels like a huge headache for anyone without a background in search optimization. I find your strategies interesting, but I remain a bit cautious about the actual results push down negative google results
Great post. I completely agree that communication is the heartbeat of any successful project. I have found that keeping stakeholders in the loop early prevents so many headaches later on More help
This is spot on. Schema markup improved visibility when running local marketing in san jose for multi-location clients. salazar digital seo services
The craftsmanship involved in floor restoration truly deserves recognition—what a skilled trade! Commerical vinyl flooring
Thanks for the tips. I dealt with a massive yellow jacket nest behind my shutters last July and it was a nightmare to handle on my own. I finally had to call in some help once they started getting near the back door professional ground nest removal
Thanks for the great information. More at Paver Installation Dix Hills NY .
I definitely learned the hard way about sealing pipe gaps around the sink pet safe cockroach control options
I rely on BoxBrownie for their 24-hour turnaround when my listings need a quick refresh. Their pricing feels fair for the quality, but I always remind clients to disclose the digital edits to buyers https://knoxxaem781.image-perth.org/do-narrow-kitchens-break-ai-staging-tools-what-you-can-do-to-fix-your-listings
Such a helpful reminder about appreciation. We used gratitude exercises from marriage counsellor near me and saw immediate improvements.
Sciatic pain was making my life miserable, but the team here knew exactly what to do. I’m finally comfortable again. Chiropractor near me
I’ve been dealing with an unflattering article from three years ago that still ranks on the first page for my brand name. It’s been tough to push it down because the site has such high authority suppress negative search results
You shouldn’t have to face the aftermath alone—resources like those at car accident lawyer are here to help!
The section on pain management documentation helps. Trackers at Truck Accident Lawyer .
It is honestly alarming to see these notices on the rise again. As an accountant, I constantly stress to my clients that even if the cash flow just isn’t there to pay the bill, you absolutely must lodge the BAS on time accountant advice for ATO debt
Капельница от похмелья направлена на восстановление водно-электролитного баланса, выведение токсинов, нормализацию работы печени и почек, а также улучшение общего состояния пациента. В клинике «Частный медик 24» мы подходим к каждому случаю индивидуально, учитывая состояние пациента, его анамнез и особенности организма. Важно, чтобы помощь была оказана вовремя, так как откладывание лечения может привести к осложнениям, таким как сердечные проблемы, психозы или нарушения сна. Выезд нарколога на дом в Самаре позволяет быстро начать лечение, не тратя времени на дорогу и дополнительные усилия.
Получить дополнительную информацию – [url=https://kapelnicza-ot-pokhmelya-samara-1.ru/]капельница от похмелья самара[/url]
I just received my jacquard suit and the fabric quality is definitely decent for the price. I am glad I waited for the sale since it was a steal at $10.72. The shipping was quick, but I do wish the color was a bit more vibrant in person More help
I had no idea the firm actually pulled off that $6.15M result in such a complex case Visit this link
I really appreciated your take on the role of a project manager. I have found that clear communication is the absolute backbone of keeping my team aligned during high-pressure sprints. It is so easy for things to get lost in the shuffle project timeline scheduling
This was quite useful. For more, visit marketing agency near me .
Dealing with those little pests in an old New London house is such a headache. I finally started sealing the pipe gaps under my kitchen sink after reading your post, and it’s already made a huge difference roaches from grocery bags
I recently started using BoxBrownie for my listings. The 24-hour turnaround saves me so much time during busy listing seasons. It really helps buyers visualize the space. Just remember to always add a disclosure statement to your photos https://numberfields.asu.edu/NumberFields/show_user.php?userid=6638368
Good advice here, particularly for first-time homebuyers. A good title search will uncover encumbrances. Ask questions during the closing process. title agency clifton park
This was very insightful. Check out website designer for more.
I appreciate the breakdown on pushing down bad search results, but I always worry about the actual investment required check here
I’ve been struggling with an old, inaccurate blog post from 2019 that keeps outranking my current service pages. It’s frustrating because it misrepresents our new pricing. I’m currently trying to push it down with fresh content, but it’s proving difficult push down competitor site
This spike in notices is honestly a wake-up call for a lot of my clients. The most critical thing I keep stressing is the importance of lodging those BAS statements on time, even if the cash flow just isn’t there to pay the tax https://www.reverbnation.com/artist/kaylayoung94
TripScan — Надежность путешествий начинается здесь
Планируете поездку и хотите убедиться, что всё пройдёт гладко? Тогда вам нужен TripScan! Это удобный онлайн-сервис, позволяющий проверить наличие ваших билетов и бронировок всего одним кликом.
[url=https://tripc63.cc]трип скан[/url]
¦ Что такое TripScan?
TripScan, также известный как трип скан, представляет собой инновационный инструмент для путешественников. Сервис позволяет быстро сверять ваши бронирования авиабилетов, отелей и арендованных автомобилей с официальными базами данных авиакомпаний и гостиниц.
Просто введите номер вашего билета или бронировки на сайте TripScan. Если информация совпадает, сервис подтвердит вашу бронь, предоставив дополнительную информацию о рейсе или отеле. Это особенно полезно перед длительными путешествиями, когда важно быть уверенным в точности всех деталей.
¦ Как пользоваться TripScan?
Использование сервиса невероятно простое:
1. Перейдите на официальный сайт TripScan (трипскан сайт) и зарегистрируйтесь или войдите в свою учетную запись.
[url=https://tripc63.cc]tripscan top[/url]
2. Выберите тип проверки: авиабилеты, отели или аренда автомобиля.
3. Введите необходимые данные вашей бронировки.
4. Получите мгновенный отчет о статусе вашей брони.
[url=https://tripc63.cc]трипскан[/url]
Это занимает считанные секунды и избавляет вас от стресса и неопределенности.
¦ Почему выбирают TripScan?
Сервис предлагает ряд преимуществ, делающих его незаменимым помощником любого путешественника:
– Быстрая проверка бронирований
– Дополнительная уверенность в поездке
– Удобство и простота использования
– Доступность круглосуточно
Кроме того, TripScan регулярно обновляется, обеспечивая точность предоставляемых данных.
¦ Где найти TripScan?
Чтобы воспользоваться сервисом, посетите официальный сайт TripScan: Здесь вы найдете всю необходимую информацию и сможете начать проверку прямо сейчас!
Также доступна мобильная версия сайта, доступная на смартфонах и планшетах. Просто откройте браузер и перейдите на трипскан сайт.
Для тех, кто хочет больше узнать о сервисе, существует подробная инструкция по использованию, доступная на главной странице.
¦ Заключение
TripScan — это надежный помощник для каждого путешественника. С ним вы можете быть уверены, что ваша поездка пройдет гладко и без неожиданностей. Проверяйте свои билеты и бронировки заранее и наслаждайтесь путешествием!
trip scan
https://tripc63.cc
This was a fantastic resource. Check out Kerner Law Group for more.
1win Visa пополнение [url=1win71849.help]1win Visa пополнение[/url]
You’re absolutely right about the value of content that answers audience questions! Read more about it at local ranking specialists .
Access control is not just about security; it’s also about efficiency! Check out access control Austin installation for more details.
Soft tissue injuries can be serious. Don’t settle fast. I consulted Truck Accident Attorney .
This post really hit home for me. I have found that clear communication is the biggest factor in keeping my team aligned during tight deadlines. I have started doing quick daily stand-ups to clear up any confusion before it builds project management problem solving
Ugh, tell me about it. We’ve been struggling with those tiny coffee-ground droppings in our pantry for weeks. I finally went around the kitchen yesterday and started sealing up the gaps around the pipes under the sink with steel wool https://atavi.com/share/xsobwmzses1a
I really appreciate the insight into these platforms. As a photographer, I love the BoxBrownie 24-hour turnaround for quick listings. Just remember to always disclose the virtual staging to potential buyers https://www.protopage.com/lydia_dunn31#Bookmarks
I’m glad I found this post. We had a massive yellow jacket nest right behind our shutters last summer and it was such a headache to deal with. My husband ended up getting stung while trying to spray it himself overhang wasp nest
плинко вывод на kaspi [url=https://plinko47590.help/]https://plinko47590.help/[/url]