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
}
Good points on stair fees and long carries. I confirmed all surcharges upfront with movers discovered on Clifton commercial movers .
Здравствуйте!
Витебский госуниверситет университет П.М.Машерова – образовательный центр. Вуз является ведущим образовательным, научным и культурным центром Витебской области. ВГУ осуществляет подготовку :химия, биология,история,физика,программирование,педагогика,психология,математика.
Полная информация по ссылке – https://vsu.by/magistrantam-i-aspirantam/magistrantam.html
курсы витебск, RETRAINING FACULTY VSU, скидки
ABOUT VSU.by, [url=https://vsu.by/sobytiya/novosti-universiteta.html]Новости машерова университета [/url], ролики
Удачи и успехов в учебе!
Hello there, just became aware of your blog through Google, and found that it is really informative.
I am going to watch out for brussels. I’ll be grateful if you
continue this in future. Lots of people will be benefited from
your writing. Cheers!
This was highly useful. For more, visit ac repair near me .
Local Perrysburg neighborhoods almost always have friendly groups perfect to manufactured homes in Ohio elkhart indiana housing options,
Yerel lezzetleri tanıtan kadın şeflerin hikâyelerini okumayı seviyorum. Derlemelere lüks vip escort üzerinden ulaşabilirsiniz.
Pro tip: ask about off-peak discounts. I scored a lower rate through Fast New Jerseys Mover’s by booking a weekday Trenton move.
You actually make it seem so easy with your presentation but I find this topic to be actually something
that I think I would never understand. It seems too complicated and
very broad for me. I am looking forward for your next
post, I will try to get the hang of it!
В этом обзоре мы обсудим современные методы борьбы с зависимостями, включая медикаментозную терапию и психотерапию. Мы представим последние исследования и их результаты, чтобы читатели могли быть в курсе наиболее эффективных подходов к лечению и поддержке.
Полезно знать – [url=https://chelnyhools.ru/lechenie-alkogolizma-v-kurske-puti-k-vyzdorovleniju/]кодирование от алкоголизма в Курске[/url]
Эта публикация содержит ценные советы и рекомендации по избавлению от зависимости. Мы обсуждаем различные стратегии, которые могут помочь в процессе выздоровления и важность обращения за помощью. Читатели смогут использовать полученные знания для улучшения своего состояния.
Связаться за уточнением – [url=http://evemakeup.ru/secrets/zdorovie/kak-pomogayut-kapelnitsyi-ot-zapoya.html]вызов нарколога на дом в Магадане.[/url]
This was a fantastic read. Check out albergue en Palas de Rei buenas reseñas for more.
Storage for tall boots was tricky until custom closet company solved it in our Atlanta closet.
If you’re cost-plus vs. set cost, make clear allowances early. I used Contractor Denver CO to locate GCs that supply open-book task setting you back and described allocation listings.
Love the linen closet transformations featured on custom closet organizers .
Этот обзор сосредоточен на различных подходах к избавлению от зависимости. Мы изучим традиционные и альтернативные методы, а также их сочетание для достижения максимальной эффективности. Читатели смогут открыть для себя новые стратегии и подходы, которые помогут в их борьбе с зависимостями.
Наши рекомендации — тут – [url=https://2prishi.ru/psihologicheskaya-otsenka-i-sostavlenie-plana-lecheniya/]kursk clinica plus[/url]
Good reminder to ask about staff training and turnover. I’ll add this as a key evaluation point on my site assisted living .
Smaller homes are better at adjusting the pace of care to match the resident, which really matters for things like toileting and mobility support. I appreciate how elderly care highlights these benefits.
Helpful for setting up a home training area — local trainers at https://www.bing.com/maps/search?lat=36.7884313&lon=-76.0612417&q=Coastal+K9+Academy&cp=36.788431%7E-76.061242&lvl=11&style=r can advise.
I like that you highlight family involvement and visiting policies. For my family, ease of visiting was a big factor. We used mapping and distance tools on senior care to narrow down suitable communities.
Appreciate the detailed insights. For more, visit Daigle Roofing and Construction .
I had my sliding door lock repaired in Houston using emergency locksmith The Woodlands TX —smooth process.
This is quite enlightening. Check out ferretería Albacete horarios for more.
Well done! Find more at reservar pensión en Arzúa .
you’re in reality a just right webmaster. The website loading speed is incredible.
It sort of feels that you are doing any distinctive trick.
In addition, The contents are masterpiece. you’ve
done a great task in this subject!
Packing up my townhouse in Hampton and looking for insured movers who handle stairs well—any recommendations? I’m considering Hampton moving companies after reading solid reviews.
Nice post on lubrication and tracks. For a local Dallas tech, I used https://www.bing.com/maps/search?lat=33.0015249&lon=-96.797049&q=Premium+Garage+Door+Repair&cp=33.001525%7E-96.797049&lvl=11&style=r .
Great customer service matters. If you booked through Buffalo car moving companies for a Buffalo car move, how responsive were they during after-hours or weather holds?
Эта статья подробно расскажет о процессе выздоровления, который включает в себя эмоциональную, физическую и психологическую реабилитацию. Мы обсуждаем значимость поддержки и наличие профессиональных программ. Читатели узнают, как строить новую жизнь и не возвращаться к старым привычкам.
Интересует подробная информация – [url=https://loverust.ru/alkogolnoe-otravlenie-simptomy-pervaya-pomoshh-i-vyzov-vracha/]вызвать врача нарколога на дом[/url]
Эта медицинская заметка содержит сжатую информацию о новых находках и методах в области здравоохранения. Мы предлагаем читателям свежие данные о заболеваниях, профилактике и лечении. Наша цель — быстро и доступно донести важную информацию, которая поможет в повседневной жизни и понимании здоровья.
Прочесть всё о… – [url=https://turbinaland.ru/pomoshh-v-borbe-s-alkogolizmom-u-blizkogo-kak-podderzhat-i-pomoch.html]clinica plus[/url]
Hi, Neat post. There is a problem along with your website in internet explorer, may test this?
IE still is the marketplace chief and a good
section of folks will pass over your fantastic writing due to this problem.
Do Woodbridge movers typically provide a Certificate of Insurance for building management? I noticed a few advertise COI on Woodbridge movers .
Публикация охватывает основные направления развития современной медицины. Мы обсудим значимость научных исследований, инноваций в лечении и роли общественного участия в формировании системы здравоохранения.
Это ещё не всё… – [url=https://military-uniforms.ru/vyvod-iz-zapoya-kak-vernut-sebya-k-normalnoj-zhizni/]наркологическая клиника в краснодаре[/url]
With havin so much content do you ever run into any problems of plagorism
or copyright violation? My site has a lot of unique content I’ve either created myself or outsourced but it appears a lot of it is popping it up all over the
internet without my agreement. Do you know any techniques to help protect against content from being stolen? I’d truly appreciate it.
If you’re on a budget, compare flat-rate vs hourly. The Best Snellville movers I found at Snellville moving companies explained both clearly.
For families living far away, knowing their loved one is in a small, attentive home can bring real peace of mind. Sites like respite care make it easier to understand how this model works.
This breakdown of the differences between Assisted Living, Independent Living, and Nursing Homes is really helpful. It makes it easier for families like mine to decide which option is best respite care
This breakdown of the differences between Assisted Living, Independent Living, and Nursing Homes is really helpful. It makes it easier for families like mine to decide which option is best respite care
Make sure your GC comprehends Denver’s snow tons and wind needs. I cross-checked architectural experience using Colorado Contractors before signing.
For apartment options close Perrysburg, synthetic properties in Ohio can present flexible rentals and community living benefits local manufactured home offers Perrysburg
For Pacific Northwest moisture complications, suited ventilation is fundamental. commercial general contractor Vancouver in Vancouver WA designed a appropriate solution for us.
Informative piece — photographing at community sports events in Melbourne is a great way to build experience; community sport images: https://www.bing.com/maps/search?lat=-37.927451&lon=145.1532699&q=Pure+Sport+Images&cp=-37.927451%7E145.153270&lvl=11&style=r
I appreciate movers who share real tracking updates. The crew I booked via Somerset apartment movers texted ETAs throughout transit.
This was nicely structured. Discover more at ac repair near me .
I’m bookmarking this for an upcoming installation. More resources at Govee RGB Outdoor Lights Vancouver
Loved the emphasis on seasonal planning. More ideas are at Luxury Holiday Lighting Vancouver
Home sellers: a repair report from central ac repair reassured our buyers during inspection.
Working from home in Sacramento when our Appliance Repair issue started. Urgent Appliance Repair Sacramento sent a technician within the hour to our place near Home of Peace Jewish Cemetery who fixed it properly the first time commercial appliance repair near me
В этой публикации мы рассматриваем важную тему борьбы с зависимостями, включая алкогольную и наркотическую зависимости. Мы обсудим методы лечения, реабилитации и поддержку, которые могут помочь людям, столкнувшимся с этой проблемой. Читатели узнают о перспективах выздоровления и важности комплексного подхода.
Ознакомьтесь поближе – [url=https://child-blog.ru/obsuzhdeniya/pochemu-stoit-vyzvat-narkologa-na-dom-v-krasnodare-preimuschestva-i-vazhnye-nyuansy.html]вытрезвитель краснодар[/url]
Packing hacks welcome! Also, does Cheap movers Dallas sell quality boxes and wardrobe cartons for DIY prep on long distance jobs from Dallas?
The seasonal setup ideas are spot-on. I’m planning a wreath-lit entry—more at Christmas Lighting Specialists Vancouver