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 interesting to see how much the telehealth landscape has shifted over the past couple of years. I’ve found the private clinic consultations much more streamlined now, but the disconnect with NHS records is still a bit confusing for my GP The original source
As a caregiver in Georgia, I am glad to see these updates, but the 1,200 mg per package limit still feels a bit restrictive for patients needing steady relief. I am trying to figure out how this affects our monthly supply costs at the dispensary Helpful resources
windsor races results
Here is my website … horse-betting.com/
As a 40-year-old parent, I definitely see myself gaming for decades more. Mobile gaming during my train commute makes the daily ride feel so much faster. I love how I can pick up right where I left off once I reach my stop gaming as relaxation
wetgeving nederland e-wedden
Feel free to surf to my site: weddenschappen snooker (https://Fr-Betting.com/)
Really appreciate this piece, thank you for sharing. Dealing with the sheer level of fatigue that comes with endo feels like a full-time job on its own some weeks https://www.mediafire.com/file/9h4rk48yskytid9/pdf-55892-57504.pdf/file
Thanks for this clear breakdown. I have been reading about private prescriptions for my chronic back pain, but the whole process seems really daunting medical cannabis for Crohn’s disease
It’s great to see more interest in wellness, but I’m always pretty skeptical of all the “miracle cure” trends I see on TikTok lately. I’ve started spending way more time researching the actual ingredients before trying anything new https://hotel-wiki.win/index.php/The_TikTok_Health_Trap:_How_to_Spot_Wellness_Misinformation_Before_You_Buy
I found the process of gathering my medical records for the clinic a bit confusing at first private cannabis prescription cost UK
It is great to see the conversation around access opening up, but I am still struggling to find clear info on the current NHS pathway https://solo.to/alan_lee88
It’s helpful to think of Assisted Living as a bridge between Independent Living and Nursing Homes. That idea was reinforced by some of the infographics I saw on respite care when we were planning care for my grandmother.
Smaller memory care homes can focus more on quality of life instead of just managing symptoms. That shift in mindset is what our family wanted. senior care helped clarify that priority.
This article clarified so many doubts I had about evaluating assisted living options. I’ll be using these tips when I research communities to link on respite care .
As someone helping a family member navigate Georgia’s medical program, the 1,200 mg limit per package is a welcome adjustment for supply consistency. It makes planning much easier compared to the constant trips we were making before Home page
This is such an important read. Honestly, the fatigue is the part nobody really talks about enough. I finally had my first pelvic floor physio session last week after waiting ages, and it’s been a total game changer for managing the daily flare-ups endometriosis symptom management
Breaker panel humming loudly— emergency electrician replaced the faulty breaker.
betrouwbare wedden op sport sites europe
I recently went through the process to see a specialist online, and it was surprisingly straightforward. The hardest part was just getting my summary of care records uploaded to the portal in time for the appointment https://www.mapleprimes.com/users/haley_adams6
Honestly, I’ve been feeling so overwhelmed lately with all the wellness trends popping up on TikTok. It’s hard to tell what’s actually legit versus just good marketing https://sergioklwv602.bearsfanteamshop.com/the-trust-pivot-why-modern-wellness-markets-now-reward-credibility-over-hype
As someone in my early thirties juggling a full-time job, I really relate to this. I find myself squeezing in mobile gaming sessions during my morning train commute more than ever. It keeps me connected to my favorite worlds even when life gets hectic https://allmyfaves.com/grant.ward10
Smart locks and sensors on entry doors have been a game changer for us. Integration with home automation was surprisingly uncomplicated. I found a setup walkthrough at local window installer .
It is great to see more awareness around this, but the whole process still feels a bit confusing. I have heard mixed things about the initial cost of private consultations versus the ongoing monthly prescriptions medical records for cannabis eligibility
It’s great to see more digital-first options opening up for patients in the UK. I’ve used telehealth for other health services, but I’m still a bit nervous about privacy when it comes to medical cannabis private cannabis clinic reviews uk
Слова “да”, “подтверждаю”, “согласен” нельзя произносить при разговоре с мошенниками,
[url=https://rosscandal.com/lenta/item/213064-gemcy-gem-cy-novaya-piramida-vasilenko]гей порно видео [/url]
так как их могут вырезать из контекста и использовать для голосового подтверждения операций, рассказала РИА Новости руководитель городского онлайн-проекта “Перезвони сам” столичного департамента информационных технологий Валентина Шилина.
[url=https://dzen.ru/a/ZLj5qIau3ivargRI]жесткое групповое порно [/url]
“В разговоре с мошенником ваше собственное слово может стать оружием против вас. Есть несколько категорий фраз, которые категорически нельзя произносить, как бы убедительно ни звучал голос на том конце провода. Слова “да”, “подтверждаю”, “согласен” — их могут вырезать из контекста и использовать для голосового подтверждения операций от вашего имени, например, в банке”, — рассказала Шилина.
[url=http://vostokmedia.com/news/2022-04-11/mvd-ob-yavilo-v-rozysk-osnovatelya-finansovoy-piramidy-life-is-good-vasilenko-601943]порно групповое жесток [/url]
“Вы даже не заметите, как ваше простое “да” превратилось в разрешение на списание денег”, — предупредила собеседница агентства.
[url=https://kinzavlg.ru/280524/best-vej-poslednie-novosti/]смотреть гей порно [/url]
Она добавила, что лучшее правило — ничего не говорить, кроме одной фразы: “Я сейчас перезвоню сам”, а затем положить трубку.
[url=https://www.mma-63.ru/301024/novosti-vasilenko-roman-poslednie-novosti/]мальчик гей [/url]
https://vklader.com/gemcy/?ysclid=miwupayl1b493943714
гей секс порно
Слова “да”, “подтверждаю”, “согласен” нельзя произносить при разговоре с мошенниками,
[url=https://treyder-rejting.ru/uniteto-live-otzyvy/]гей порно видео [/url]
так как их могут вырезать из контекста и использовать для голосового подтверждения операций, рассказала РИА Новости руководитель городского онлайн-проекта “Перезвони сам” столичного департамента информационных технологий Валентина Шилина.
[url=https://www.vokalcherezbokal.ru/151124/novosti-vasilenko-roman-poslednie-novosti/]русское гей порно [/url]
“В разговоре с мошенником ваше собственное слово может стать оружием против вас. Есть несколько категорий фраз, которые категорически нельзя произносить, как бы убедительно ни звучал голос на том конце провода. Слова “да”, “подтверждаю”, “согласен” — их могут вырезать из контекста и использовать для голосового подтверждения операций от вашего имени, например, в банке”, — рассказала Шилина.
[url=https://vestnik-jurnal.com/index.php/wiki/item/65408-roman-viktorovich-vasilenko-rossiyskiy-piramidschik]смотреть гей порно [/url]
“Вы даже не заметите, как ваше простое “да” превратилось в разрешение на списание денег”, — предупредила собеседница агентства.
[url=https://brokertribunal.com/investment-projects/hermes-management-ltd]порно групповое жесток [/url]
Она добавила, что лучшее правило — ничего не говорить, кроме одной фразы: “Я сейчас перезвоню сам”, а затем положить трубку.
[url=https://halyq-uni.kz/news/20347-karzhy-piramidalarynyn-tizimi-zhariialandy/]жесткое порно бесплатно [/url]
https://blog-club.org/post-group/roman-viktorovich-vasilenko-rossijskij-moshennik/
гей секс порно
It’s great to see more awareness about the telehealth options, as navigating the private clinics can still feel pretty daunting for newcomers https://alice-lopez06.raindrop.page/bookmarks-71838929
Really appreciate this piece. Honestly, the fatigue is the part people just don’t seem to get. I’ve been waiting for a specialist appointment for over two years now, and days where I just can’t get out of bed are the hardest endometriosis and mental health support
It’s definitely about time there’s more transparency in the wellness space. I’ve spent way too long researching ingredients just to figure out what’s actually legit versus marketing fluff wearable technology health
It’s great to see digital access becoming the norm, as it definitely makes things more accessible for those of us living far from specialist clinics https://sticky-wiki.win/index.php/How_Follow-Up_Consultations_Work_in_a_Digital-First_Healthcare_Model
Thanks for the clear breakdown on the current process. I have been looking into this for a while but the record-sharing part feels a bit daunting https://atavi.com/share/xvvpqlzrg0gl
For bonuses paid in BTC/ETH, constantly read betting terms– some sites lock you into specific slots. I have actually been utilizing mobile online crypto casino to find reasonable rollover requirements.
It’s so validating to read this. Honestly, the fatigue is the hardest part to explain to friends when you’re trying to keep up with work digital healthcare UK
Ask if excavation spoils will be hauled or reused—affects cost. Clear estimates via septic pumping helped us decide.
”Eagerly awaiting responses shared openly creates opportunities fostering growth enhancing collective well-being surrounding this niche focusing uniquely!” ## Invisible Braces
It’s easier to maintain routines like morning grooming or evening walks when the environment is small and predictable. That’s a big plus for homes like the ones featured at respite care .
Your checklist for touring a memory care community is very practical. I’ll bring it along when I visit a few of the locations I found on respite care .
As an adult child living in another state, the clarity here helps me talk more confidently with my siblings. We’ve been using assisted living to compare communities and learn what each level of care actually offers.
It’s really interesting to see how the UK is finally moving toward a more digital-first approach for medical cannabis access. I’ve used telehealth for other health issues and it definitely makes the process less intimidating https://privatebin.net/?40db46ebf00d5a5f#9V5bRBCFhHR9KHg7G7QN867V68UWtou5tLspkKBJJHJ5
I’m glad this article brings up the confusion between CBD and THC. I constantly see people mixing them up in shops, which makes it super tricky for someone just looking for basic relaxation https://atavi.com/share/xvvppxz1hyo5a
Nicely done! Find more at opiniones abogados Coruña .
Check if they offer tree inventory and mapping for larger properties. I found inventory templates at commercial tree service .
Interested in understanding how feedback culture works within organizations, especially regarding # # anyKeyWord#’s approach. Leadership coaching san francisco
New buyers should definitely price-shop. A יועץ משכנתא does this daily: ייעוץ להבראה כלכלית .
It is honestly such a relief to see more open talk about this now. That constant fatigue is the part nobody really seems to understand, even with the video consults making it a bit easier to get seen https://madison-flores93.raindrop.page/bookmarks-71839236
It’s great to see the UK finally modernizing access to medical cannabis through these digital clinics. I’ve found the convenience of telehealth helpful, but I do worry a bit about data security https://pixabay.com/users/56250447/
http://squarebrackit.de/
Das Projekt Squarebrackit etabliert sich als ein spezialisierte Agentur ausgerichtet auf die deutsche Wirtschaftslandschaft, das liefert professionelle Begleitung fuer alle die Ergebnisse suchen, sich auszeichnend durch auf Vertrauen und Transparenz. Besuchen Sie die Website auf der offiziellen Website.
Appreciate the detailed information. For more, visit demanda ante el Juzgado de lo Social .
Chơi thử miễn phí trước khi cược thật ở rikbet nhà cái uy tín cá cược online rikbet
Appreciate the comprehensive advice. For more, visit taxi Camino de Santiago .
This was highly helpful. For more, visit Bayports’ #1 Power Washing Pros | Roof & House Washing .