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
}
I’ve been thinking about therapy but one thing that worries me is how awkward that first session might feel. It’s hard opening up to someone new, especially when you’re not sure if they really understand what men go through sexual health counselling Vancouver men
I’ve been testing Suprmind’s $19 Spark plan and really like the Red Team mode for security checks, but I noticed it doesn’t support PPTX exports like MultipleChat does. Has anyone found a good workaround for sharing presentations directly from Suprmind? Find more information
I’ve been using Shippo mainly for their 100+ integrations, which save me a ton of time syncing everything up. But Pirate Ship’s $50 credit on free accounts caught my eye too—pretty sweet deal for newcomers trying to keep costs down Article source
I really appreciate that Suprmind offers the $19/mo Spark plan with the 7-day free trial and no credit card required. It makes testing the platform way less stressful compared to ChatHub. Also, the Red Team feature sounds promising for security https://tiny-wiki.win/index.php/ChatHub_vs_Suprmind_for_Consultants_Writing_Client_Decks_and_Memos
I’ve been using TypingMind with the Debate mode for a few weeks and really appreciate the dynamic back-and-forth it encourages. However, I’m curious how Suprmind’s BYOK (bring your own key) encryption stacks up in terms of real privacy advantages Website link
This was very well put together. Discover more at bufete de abogados Coruña .
I’ve been using Suprmind’s Decision Validation Engine and it really helped streamline my project planning by offering solid feedback loops. For just $19 a month, it’s a great value compared to AI Fiesta’s features Click for info
I really appreciated this article because therapy for men can feel intimidating. One thing I worry about is the cost—sessions can add up quickly and I’m not sure what’s covered by insurance here in Vancouver the cove counselling vancouver
I love how the article brought back butterfly clips! They were such a fun and quirky accessory in the early 2000s. I’ve been hesitant to try them again, but your styling tips make it feel modern instead of costume-y y2k hair accessories trends
Здорова, народ Отец не выходит из штопора Соседи стучат в стену В больницу тащить страшно Короче, врачи приехали и поставили систему — капельница после запоя цена фиксированная Поставили капельницу с детоксикационным раствором В общем, жмите чтобы сохранить — капельница запой [url=https://detoks.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru]https://detoks.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru[/url] Звоните прямо сейчас Перешлите тем кто в такой же ситуации
you can try this out https://simple-info.at/
Люди, помогите дельным советом. Муж просто потерял себя и уничтожает свое здоровье. Вся семья в дикой истерике, В обычную государственную больницу тащить человека просто страшно до тех пор, не нашли проверенную медицинскую службу, начиная от качественной детоксикации на месте и заканчивая подбором медикаментов. Сразу профессионально поставили капельницу с детоксикационным раствором,
Кому тоже экстренно необходим проверенный круглосуточный телефон наркологии, смотрите sami все расценки и условия по ссылке капельница от запоя в стационаре [url=https://nedorogoy.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru]https://nedorogoy.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru[/url] Не ждите, пока состояние станет еще хуже, обязательно перешлите этот пост тем, кто тоже сейчас находится в такой же критической ситуации!
Thanks for the detailed comparison! I’ve noticed Suprmind’s Red Team mode can be pretty useful for testing responses, but MultipleChat’s 25+ templates seem better for quickly setting up different conversation flows Suprmind vs MultipleChat
This was very enlightening. For more, visit salarios atrasados .
I’m really impressed that Suprmind offers a 7-day trial with no credit card required—that’s a huge plus for anyone who just wants to test things out without commitment. ChatHub’s cookie passthrough sounds neat, but I value transparency and ease more get more info
I’ve been using Shippo mainly because of their 100+ integrations, which makes syncing with my sales channels way easier. The $50 credit for eligible free accounts was a nice bonus when I started https://simonoaeq490.yousher.com/does-pirate-ship-have-an-api-for-custom-fulfillment-workflows
I’ve been trying out Suprmind’s Debate mode, and it really helps clarify pros and cons in complex topics, which TypingMind lacks. However, TypingMind’s $39 lifetime deal with self-hosting and BYOK keys is tempting for more privacy-conscious users https://iris-wiki.win/index.php/I_Need_Board-Ready_Memos_%E2%80%94_Is_Suprmind_Better_for_Deliverables%3F
I’ve been using Suprmind’s Decision Validation Engine for a few weeks now, and it’s a game-changer for making complex choices more structured and less stressful. At $19, it feels like solid value compared to other pricey AI tools Click to find out more
I love how the article brought back butterfly clips! They were such a fun and quirky accessory in the early 2000s. I’ve been hesitant to try them again, but your styling tips make it feel modern instead of costume-y https://unsplash.com/@dennis_stone42
This was highly useful. For more, visit catálogo de enfermedades reumatológicas .
Екатеринбург, всем привет Ситуация критическая Дети напуганы В больницу тащить страшно Короче, только капельница реально спасла — капельницы от похмелья с препаратами Поставили капельницу с детоксикационным раствором В общем, телефон и цены тут — капельница от похмелья купить [url=https://detoks.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru]https://detoks.kapelnicza-ot-zapoya-ekaterinburg-nmx.ru[/url] Не ждите пока станет хуже Перешлите тем кто в такой же ситуации
Thanks for sharing this article. I’ve been thinking about therapy for a while but worry about the cost, especially in Vancouver where everything feels expensive. It’s good to know there are options, though men’s mental health bc
I’ve been trying out Suprmind’s $19 Spark plan, and while I appreciate the variety of 25+ templates, I’m curious how it stacks up against MultipleChat’s Red Team mode for handling sensitive queries Article source
Continue Reading https://simple-info.at/
I’ve been using Shippo mainly because of the 100+ integrations—it really streamlines my workflow. The branded tracking pages are a nice touch too, makes my small business look more professional https://campsite.bio/nancy.perry97
quote basketball wetten heute, Randi, dass
I’ve tried both Suprmind and ChatHub, and honestly, the 7-day trial with no card on Suprmind feels way more user-friendly. It’s nice not to worry about canceling before getting charged ChatHub browser extension
I’ve been testing Suprmind for a few weeks, mainly because of the $39 lifetime deal, and really like the Debate mode for brainstorming Debate mode AI
beste bonusbedingungen sportwetten
Feel free to surf to my blog post; olympia basketball wetten – Elsa,
I’ve been using Suprmind’s Decision Validation Engine on the $19 plan and honestly, it’s a game changer for my workflow. It helps me catch biases in my reasoning that I didn’t even realize I had. AI Fiesta’s image generation is cool but felt a bit limited AI image generation in chat
I love how you brought back the baby tee trend! It’s crazy to think how such a simple piece was everywhere in the early 2000s. Seeing celebs like Olivia Rodrigo rocking updated versions makes me want to try pairing one with some modern high-waisted jeans y2k street style outfits
I’ve been testing Suprmind’s Debate mode and found it surprisingly helpful for refining arguments, but TypingMind’s $39 lifetime deal with self-hosting options is really tempting for long-term control and privacy https://www.animenewsnetwork.com/bbs/phpBB2/profile.php?mode=viewprofile&u=1219883
Thanks for the comparison! I’m curious—since Suprmind offers 25+ templates while MultipleChat focuses more on the five models, do you find that the templates actually speed up workflow MultipleChat alternative
I’ve been using Shippo for a bit and really like the 100+ integrations—it makes syncing with my shop super smooth. The branded tracking pages also add a nice professional touch for customers Find out more
I’ve been trying both and honestly, the $19/mo Spark plan on Suprmind feels more straightforward compared to ChatHub’s setup. The 7-day trial with no credit card is a nice touch too—it lets you really test things out without commitment Suprmind review
I’ve been using Suprmind’s Decision Validation Engine for a few weeks and it really helps me avoid costly mistakes by double-checking my assumptions. For $19 a month, it’s a steal compared to other tools that don’t offer the same depth of insight Debate mode AI for decisions
Thank you for the guide to long-distance moves from Corona. I started with local quotes using Corona international movers and compared options.
I’ve been testing both Suprmind and TypingMind, and while TypingMind’s Debate mode is a nice touch for exploring different perspectives, Suprmind’s BYOK feature is what really stands out for me in terms of data privacy Look at this website
“Thanks for putting this together. I think your point about asking about insurance, timelines, and packing support is especially important when hiring movers.” industrial movers Plainfield
Clearly presented. Discover more at painting company near me .
As a freelance writer, I appreciate that Perplexity offers 5 Deep Research queries per day on the free plan—that’s pretty generous for someone just testing the waters without a big budget https://www.4shared.com/office/QRUzRcc9jq/pdf-64481-99899.html
As a freelance writer, I found the 5 Deep Research queries per day on the free plan really helpful to get started without immediate costs https://high-wiki.win/index.php/Enterprise_Org_Repository:_500_Files_-_Is_That_Per_Org_or_Per_User%3F
Gum disease care can help protect your smile for the long term. Ventura residents can find helpful information at Gum Disease Treatment in Ventura .
Great topic for anyone planning a move in or out of Michigan. Detroit car moving companies offer different services, so using Detroit car moving companies to compare options is a smart idea.
As a freelance writer, I’ve been eyeing Perplexity’s pricing, especially the 5 Deep Research queries per day on the free tier Model Council Perplexity
Вывод из запоя в стационаре — это профессиональная наркологическая помощь, которая проводится под медицинским наблюдением и с учетом физического состояния человека. Такой формат выбирают, когда домашнего лечения уже недостаточно, когда запой длится несколько дней, появились тремор, страх, бессонница, скачки давления, нарушения со стороны сердца, печени, жкт или нервной системы. В стационаре врач проводит осмотр, оценивает тяжесть интоксикации, подбирает препараты, контролирует пульс, давление, сон, уровень жидкости и общее самочувствие.
Подробнее – [url=https://vyvod-iz-zapoya-v-statsionare-v-gelendzhike3.ru/]нарколог вывод из запоя в стационаре геленджик[/url]
As a freelance writer, I’m really interested in the 5 Deep Research queries per day included in the free plan—sounds like a perfect fit for quick, in-depth fact-checking without instantly upgrading https://www.animenewsnetwork.com/bbs/phpBB2/profile.php?mode=viewprofile&u=1219893
BSA Insurance claims integrates expertise along with potent campaigning for, showing they’re the most ideal independent adjusters. Inspect the hyperlink at BSA Claims Solutions independent insurance adjuster .
I’ve been thinking about starting therapy, but the idea of the first session feels really awkward to me. Especially in person, I worry about saying the wrong thing or not connecting with the therapist right away get more info
Вывод из запоя в стационаре в Москве требуется в случаях, когда человек пьет несколько дней, не может самостоятельно остановиться, плохо спит, отказывается от еды, испытывает тремор, тревогу, боли, скачки давления или признаки острой интоксикации. В такой ситуации домашнего ухода часто недостаточно: нужна медицинская помощь, контроль состояния, грамотная детоксикация организма и возможность быстро получить обследование. Стационарное лечение помогает безопасно выйти из запойного состояния, снизить нагрузку на сердце, печень, нервную и сосудистую системы, а также начать полноценное восстановление.
Подробнее тут – [url=https://vyvod-iz-zapoya-v-stacionare-v-moskve14-2.ru/]vyvod-iz-zapoya-v-stacionare-v-moskve14-2.ru/[/url]