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
}
First-rate solution every single time with The Master’s Lawn & Pest! They’re most certainly the best landscaping near me in St Augustine. landscaping
We just moved across the water to Virginia Beach last month and finding movers who actually know how to handle an antique piano was a total nightmare. Most companies seemed terrified of the stairs but the crew we finally hired were pros same day movers
Navigating this decision is honestly one of the most exhausting things I’ve ever done for my dad. It feels like you’re constantly second-guessing everything how to choose memory care
Helpful article for making informed decisions related to Nasha Mukti Kendra in Noida. Nasha Mukti Kendra in Noida
This post is educational for anyone considering Rehabilitation Centre in Noida. Rehabilitation Centre in Noida
Your tip about tarping during rain is great. I get weather advice from providers on dumpster rental near me scottsdale .
This really hits home. I’ve been struggling to get a simple face-to-face GP appointment for a back issue for weeks, and the whole referral process feels like a total maze. It’s hard to know which way to turn when you’re just trying to get some clarity nhs 111 online vs phone
cum sa ma inregistrez pe melbet [url=http://melbet63149.help]http://melbet63149.help[/url]
Exceptional solution each time with The Master’s Lawn & Pest! They’re certainly the best landscaping near me in Gainesville. landscaping near me
The team from house cleaning company near me Sarasota left our home smelling fresh, not perfumy.
1win live bet [url=https://1win49027.help/]1win live bet[/url]
Proposed at Millennium Park with a ring from dimend SCAASI and everything was most appropriate. The ring changed into even greater pleasing outdoor in the sun than in the shop. She pointed out sure in the present day. Chicago Jewelry Store
It’s really interesting to see how these options are gaining more traction lately. When I chatted with my GP about trying something outside the standard route, I found it quite difficult to get a proper conversation going Click here for more info
If you’re searching for the “best Sushi near me” in St. Augustine, Ginger Bistro is a winner! sushi st augustine
Терапевтический алгоритм в стационаре не сводится к единой разовой манипуляции. Это последовательная система диагностики, стабилизации, медикаментозной поддержки и подготовки к амбулаторному этапу, выстроенная с учетом современных стандартов наркологии 2026 года. При поступлении врач проводит детальный неврологический и соматический осмотр, собирает развернутый анамнез, оценивает когнитивные функции и при необходимости назначает лабораторные исследования. На основе полученных данных формируется индивидуальный протокол, учитывающий возраст, длительность интоксикации, наличие хронических заболеваний и переносимость лекарственных компонентов. Мы отказываемся от универсальных схем в пользу точного дозирования, что ускоряет восстановление метаболических функций и снижает вероятность побочных реакций.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-v-staczionare-nizhnij-novgorod-10.ru/]вывод из запоя в стационаре в нижнем новгороде[/url]
Запой сопровождается выраженной интоксикацией, нарушением сна, слабостью, тревожностью и колебаниями давления, что характерно для алкоголизма и других форм зависимости. При этом самостоятельный выход из состояния часто оказывается затруднённым из-за ухудшения самочувствия и невозможности контролировать симптомы. В таких случаях выезд нарколога позволяет начать лечение без задержек и помочь пациенту снизить нагрузку на организм за счёт отсутствия транспортировки.
Получить дополнительные сведения – http://vyvod-iz-zapoya-na-domu-sankt-peterburg-8.ru/
If you’re browsing for the “most tasty Chinese restaurant near me” around St. Augustine, Ginger Bistro is a winner! chinese near me
This is a really interesting perspective on integrating alternative care. My main worry is how to bring this up with my GP without feeling dismissed, especially as the referral pathways feel so rigid these days role of clinician as guide
Запой сопровождается выраженной интоксикацией, нарушением сна, слабостью и нестабильностью работы сердечно-сосудистой системы, что характерно для алкоголизма и других форм зависимости, включая наркомании. Самостоятельный выход из этого состояния может быть затруднён и сопровождаться усилением симптомов. Медицинская помощь на дому позволяет снизить риски и начать восстановление под контролем специалиста, помогая человеку быстрее стабилизировать состояние.
Разобраться лучше – [url=https://vyvod-iz-zapoya-na-domu-sankt-peterburg-12.ru/]www.domen.ru[/url]
Trusted solution every single time with The Master’s Lawn & Pest! They’re definitely the most effective lawn care near me in St Augustine lawn care
Vin88 là nhà cái cá cược top đầu với hệ thống trò chơi đa dạng: thể thao, casino trực tuyến, slot và bắn cá. App mượt, rút tiền nhanh, ưu đãi lớn, bảo mật tuyệt đối. Trải nghiệm sảnh game sống động và dịch vụ hỗ trợ 24/7 chuyên nghiệp bbc
This was a wonderful guide. Check out Yannis Divramis SEO expert for more.
I used to be able to find good advice from your content.
kasiino pakkumised
It is interesting to see how these options are becoming more mainstream. I had a conversation with my GP recently about integrating different approaches alongside standard care. It was a bit of a struggle to get a straight answer on access, though https://finnfazr460.theburnward.com/alternative-therapy-vs-complementary-therapy-navigating-your-healthcare-choices
1win crash necə oynanır [url=www.1win81936.help]www.1win81936.help[/url]
I have actually been searching for the leading Chiropractor near me in St Augustine and maintained seeing terrific reviews concerning Pain Relief Centre. After my initial appointment, I recognized why– expert care, tailored therapy, and real outcomes chiropractor st augustine
melbet depunere cu qiwi [url=http://melbet63149.help/]http://melbet63149.help/[/url]
Really interesting read. I have noticed more people looking into these options lately. When I tried to bring it up with my GP recently, they were quite dismissive, which was a bit disheartening private vs NHS treatment wait times
Hi are using WordPress for your site platform? I’m new to
the blog world but I’m trying to get started and create my own. Do
you need any coding knowledge to make your own blog?
Any help would be really appreciated!
This article really hits the mark on what defines a top-tier lawyer. I firmly believe active listening stands above everything else when handling a difficult client call. It builds trust far faster than any legal jargon ever could https://wiki-site.win/index.php/How_Do_Lawyers_Avoid_Mistakes_When_Drafting_Contracts_or_Motions%3F
В этой статье мы рассматриваем разные способы борьбы с алкогольной зависимостью. Обсуждаются методы лечения, программы реабилитации и советы для поддержки близких. Читатели получат информацию о том, как преодолеть зависимость и добиться успешного выздоровления.
Лови подробности – [url=https://chistotainfo.ru/zapah/effektivnye-metody-ustraneniya-zapahov-alkogolya]вывод из запоя дешево[/url]
It’s really interesting to see how things have shifted over the years. I remember when you just did whatever the GP said without a second thought. Nowadays, I feel much more empowered to ask questions about my treatment options Check out this site
Ganesha Gold is built for high-volatility profiles and visually intense bonus rounds.
I savour, lead to I discovered just what I used to be taking a look for.
You’ve ended my four day lengthy hunt! God Bless you man. Have a nice
day. Bye
This article hit the nail on the head regarding what separates good lawyers from great ones. For me, active listening stands out as the most crucial skill here
1win lucky jet demo [url=http://1win49027.help]http://1win49027.help[/url]
It’s really interesting to see how things have changed over the years. I think the biggest takeaway for me is realising just how important it is to be comfortable asking questions during consultations https://www.tumblr.com/magnificentapexwonder/815958380257689600/how-to-navigate-requesting-a-second-opinion-in-the
Really interesting read. I’ve noticed more people in my area looking into these options lately. When I brought up a few ideas with my own clinician, they were surprisingly open to discussing how they might fit alongside my usual routine https://www.protopage.com/brianna-sanchez77#Bookmarks
1win USDTga yechish [url=www.1win49027.help]www.1win49027.help[/url]
Решение о помещении пациента в стационар принимается на основе объективных медицинских критериев, а не только по желанию родственников. К показаниям относятся: запой длительностью более трех суток, выраженные симптомы абстиненции, наличие в анамнезе алкогольных делириев или судорожных эпизодов, сопутствующие хронические заболевания печени, поджелудочной железы, сердца или нервной системы. Отдельным фактором выступает полинаркомания или сочетание алкогольной зависимости с приемом психофармакологических препаратов без назначения врача. В таких ситуациях риск развития тяжелых осложнений возрастает многократно, и амбулаторный формат не обеспечивает необходимого уровня контроля. Госпитализация позволяет провести полноценную диагностику, включая ЭКГ, экспресс-анализы крови, оценку неврологического статуса и мониторинг сатурации, что формирует точную картину состояния и исключает назначение шаблонных схем.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-v-staczionare-nizhnij-novgorod-6.ru/]вывод из запоя в стационаре анонимно в нижнем новгороде[/url]
Thanks for the great tips. Discover more at Plumbing supply store near me .
I really appreciate this perspective shift. For so long I felt like I was just scraping by to survive the day, but your point about asking better questions really clicked for me eligibility mental health services UK
Trusted solution whenever with The Master’s Lawn & Pest! They’re most certainly the best lawn care near me in Gainesville Fl. lawn care
I love the idea of digging into the history of these venues—it’s so fun to ask what the building used to be! We’re currently planning our wedding for next summer here in the Pacific Northwest, and I’m definitely going to research the past of our shortlist historic venue modern comforts
This article hits the nail on the head. I think active listening makes the biggest difference in our practice. When I focus on truly hearing the concerns during a tense client call, I build much better trust and rapport Go to this site
This was quite informative. More at commercial privacy film .
Choosing a memory care facility is honestly so overwhelming. My mom has been in a few places, and the transition is never easy, but this article really hits on the important stuff care conference nursing home
It’s really interesting to see how much more agency we have now compared to years ago. Personally, I’ve found that just being encouraged to ask more questions during consultations has made a massive difference in how I manage my own health NHS private crossover care
If you’re searching St. Augustine, you’ll rapidly see why locals state the most effective agency for homeowners insurance in and near St. Augustine is Fender Insurance Agency home insurance st augustine
Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
Получить дополнительную информацию – [url=https://malishi.online/bolezni/poeziya-isceleniya-i-realnye-shagi-k-svobode/]цены на вывод из запоя на дому[/url]