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
}
Thanks for sharing these tips. For local gutter professionals in Rigby ID, try Gutter Services in Rigby ID .
I really needed to read this today. I’m so guilty of staying up way too late finishing laundry or scrolling through my phone, and then I’m a total zombie when the kids wake up early. It definitely affects my patience https://www.4shared.com/office/nuFJhkH1ku/pdf-32070-30457.html
Great to see pelvic floor mentioned—London Ontario specialists are connected through perimenopause treatment london ontario .
I love this list! Blade Runner 2049 is definitely my go-to when I want to relax because the visuals are just so stunning and immersive. It is the perfect way to zone out after a long week movies like ex machina
I’ve been looking into sleep gummies lately because my sleep schedule is a total mess. I found that starting at 15mg worked best for me without feeling groggy the next morning https://golf-wiki.win/index.php/How_to_Avoid_THC_If_You%E2%80%99re_Sensitive:_A_Consumer_Editor%E2%80%99s_Guide
Appreciate the comprehensive insights. For more, visit contratar alojamiento Camino de Santiago .
As someone who grinds ranked matches until midnight, I totally get the struggle of trying to switch off afterward. My brain is usually still buzzing with play-by-plays best cbd gummies for deep sleep
As a local actor, I’ve definitely been looking into CBD to help me settle those pre-show nerves before hitting the stage in Silver Lake. The tension gets real right before curtain call! I’ve been a bit hesitant, though CBD certificate of analysis
Living in McKinney, you know how brutal these Texas summers get. My unit has been dealing with really weak airflow lately and it’s getting so stuffy inside https://sirachapete736.gumroad.com/
OBG came in with a lower price than two other quotes I had. The price-match guarantee was not even needed in the end. The garage is solid and well finished. Highly recommend for Glasgow customers. Concrete Garages Glasgow
OBG came highly recommended by a neighbour in Giffnock and they did not disappoint. The team was friendly, the build quality is excellent, and the 10-year warranty gave me real confidence. Very happy to recommend. Garden Room Glasgow
В статье по вопросам здоровья мы рассматриваем актуальные проблемы, с которыми сталкивается общество. Обсуждаются заболевания, факторы риска и важные аспекты профилактики. Читатели получат полезные советы о том, как сохранить здоровье и улучшить качество жизни.
Подробная информация доступна по запросу – [url=https://nosoldat.net/kapelnitsa-ot-pokhmelya-mgnovennoe-oblegchenie-posle-veseloy-nochi/]Капельница от похмелья[/url]
Helpful checklist — for comprehensive tree care in New Albany, I recommend tree service in New Albany Indiana Cummins Tree Service .
I really needed this reminder. I’m so guilty of staying up late doing dishes or scrolling through my phone, which just leaves me exhausted and cranky with the kids in the morning. It’s hard to be present when I’m running on caffeine and regret Visit this page
I honestly think Arrival is the perfect pick for a cozy night in. The score is so haunting and atmospheric that it completely pulls you into the story. To really get the most out of the experience, try dimming the lights all the way down how to enjoy a movie alone
Man, that 3:30 AM alarm always hits differently after a long day in the mountains. I’ve definitely felt that mid-week soreness mule deer backcountry recovery
I’ve been looking into sleep gummies lately but felt overwhelmed by all the options out there. I started with a 15mg dose last week, which definitely helped me wind down without feeling groggy the next morning Discover more here
Comment Sandy Utah Plumber Experience 02
Same-day service made all the difference when our water heater decided to quit. Had hot water back before dinner. Incredibly relieved. Plumber Sandy
Appreciate the great suggestions. For more, visit portal extranjería España .
Με τόσες αυτόματες Μεταφράσεις εκεί έξω, είναι σημαντικό να υπάρχει ανθρώπινος έλεγχος. Το μετάφραση πτυχίων για εργασία συνδυάζει τεχνολογία και επαγγελματίες μεταφραστές, κάτι που λύνει τα χέρια.
For reliable, affordable care in Pattaya, I recommend Takecare Clinic. Appointment and contact info via rabies vaccine in Pattaya .
Man, I feel this. After grinding ranked matches until late, my brain is usually still firing on all cylinders when I try to hit the pillow. I’ve started making sure my room is ice cold and strictly dimming my lights right after my last match to help https://eleanorsimpressiveinsight.tearosediner.net/cbd-gummies-vs-cbd-oil-for-sleep-which-is-easier-at-night
Honestly, this is such a mood. After a long curtain call, my brain just stays in performance mode for hours, making it impossible to actually wind down. I’ve been curious about trying tinctures to finally hit that reset button https://www.demilked.com/author/caleb_chambers98/
Ugh, living here in McKinney, our AC is basically a life support system. Mine has had really weak airflow lately, and it’s getting pretty stuffy inside https://unsplash.com/@claire_zhou82
If your HOA in Long Beach restricts big rigs, Long Beach Auto Transport arranged a nearby meetup to avoid fines.
I really needed this today. I’m so guilty of staying up way too late scrubbing the kitchen or scrolling through my phone while exhausted. It’s no wonder I’m so cranky the next morning Helpful resources
I completely agree with the relaxing sci-fi picks. Arrival is such a perfect choice for this because that sweeping, ethereal score always helps me settle into a calm headspace. It’s exactly the kind of movie that needs total immersion organic cbd gummies for evening use
Man, I know that struggle of waking up to an early alarm feeling like a train wreck. Ever since I started taking magnesium glycinate before bed, the recovery has been a game changer. The article’s mention of only 4 hours of sleep really hit home for me https://www.inkitt.com/brenda_sanchez
I’ve been looking into trying CBD gummies for my restless nights, but there are just so many brands out there. I started with a 15mg dose to see how my body would react, and it’s been hit or miss so far residual solvents CBD test
Man, I feel this. After grinding ranked sessions late at night, my brain is still buzzing for hours, even after closing the game https://www.animenewsnetwork.com/bbs/phpBB2/profile.php?mode=viewprofile&u=1197534
Thanks for the comprehensive read. Find more at สล็อตเว็บตรง .
I really needed to read this today. I’m so guilty of staying up way too late to finish chores or mindlessly scrolling through my phone, and then I’m just a zombie when my kids wake me up in the morning nighttime routine relaxation
As someone constantly hitting the stage for late gigs around Silver Lake, I’ve been curious about adding this to my post-show routine. After curtain call, it’s always such a struggle to switch off. This sounds like a game changer for those long nights More help
Dealing with this Texas heat is brutal when your AC starts acting up. We had ours blowing nothing but warm air last night, and it’s always a struggle finding someone reliable in McKinney ac high humidity in house
В статье рассматриваются различные стратегии борьбы с зависимостями, включая проверенные методы и реальные истории успеха. Читатель узнает, какие подходы наиболее эффективны и как начать путь к выздоровлению.
Что скрывают от вас? – [url=http://hramy.org/blog/pomoshh-narkologa-na-domu-v-tveri-komfort-i-konfidenczialnost.htm]нарколог на дом тверь[/url]
I absolutely love the idea of a chill sci-fi night. Arrival is always my top pick because the visuals are just so stunning and hypnotic. It’s the perfect way to unwind after a busy week https://atavi.com/share/xw1d2nzn7i2c
Man, waking up at 4:00 AM for a climb is rough on the joints. That 48-hour recovery window you mentioned really hits home when my muscles feel like lead elk hunting physical recovery tips
I appreciate the balanced view on HRT; I prepared questions for my London clinic using a checklist from menopause symptoms .
I’ve been experimenting with CBD gummies for a while now, and starting low definitely helps. I personally found that 15mg works best for my sleep without feeling groggy the next morning high fructose corn syrup gummies
Honestly, I feel this. After grinding ranked sessions late at night, my brain is usually still buzzing and it takes forever to actually fall asleep how to wind down after ranked matches
Excellent reminder to transparent particles from valleys and coffee spots. We embrace this as a favourite upkeep concept for all home owners who use Gikas Roofers reviews .
I was impressed that OBG does not ask for full payment upfront. After reading about other customers having issues with different companies, this reassured me greatly. The garage was installed as agreed and on schedule. Concrete Garages Glasgow
I liked this article. For additional info, visit nutricionista cerca de mi online .
Seven months into owning my OBG garden room and it has been through a Scottish winter without any issues. Warm, dry, well insulated. The build quality is clearly high. Very pleased with the investment. Garden Room Glasgow
I totally relate to this. Lately, I’ve been staying up way too late finishing laundry and scrolling on my phone, only to wake up exhausted and irritable with the kids. It’s definitely time for a change https://abundant-moustache-e5b.notion.site/Sleep-isn-t-a-luxury-it-s-the-key-to-staying-patient-and-present-Better-rest-37d742f4a94b8072b272d7c30f228339
This was highly helpful. For more, visit ofertas de perfumes .
Travel insurance accepted and great follow-up care—see ear cleaning in Pattaya for Takecare Clinic Doctor Pattaya info.
Эта публикация посвящена актуальным вопросам современной медицины и здравоохранения. Мы обсудим новейшие технологии диагностики и лечения, а также их влияние на продолжительность и качество жизни. Читатель найдет здесь информацию о научных исследованиях и перспективных разработках, доступно изложенную для широкой аудитории.
Более того — здесь – [url=https://newsprofit.info/preimushhestva-vyzova-narkologa-na-dom-i-kak-on-pomogaet-pri-lechenii-zavisimosti.html]clinica plus[/url]
Nice content. If you need storm recovery roofing in Benbrook, check google.com to find a Roofing company Benbrook TX.
Man, that 3:00 AM alarm hits different after a long day in the stand. I’ve really started relying on magnesium glycinate to help me actually recover so I can wake up for the next sit without feeling like a total wreck Find more information