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
}
Частный наркологический центр предлагает помощь круглосуточно. Врач может приехать на дому, провести обследование, определить тяжесть абстинентного синдрома и решить, допустима ли терапия вне стационара. При серьезных нарушениях лечение продолжают в клинике, где доступна круглосуточная медицинская помощь. Все назначения выполняются индивидуально: учитываются возраст обратившегося, длительность запоя, хронические болезни, принятые медикаменты, седативные средства, наркотики и иные вещества. Работа строится анонимно и конфиденциально.
Изучить вопрос подробнее – [url=https://4.vyvod-iz-zapoya-v-ekaterinburge16.ru/]помощь вывод из запоя[/url]
This time, I wanted to do things differently. I wanted something that would turn heads and make the experience memorable. After comparing a few companies, I found the right one. miami luxury car rental — they had an incredible selection. The staff helped me pick the perfect car for my plans. The experience was everything I had hoped for. If you’re visiting Miami and want a car that matches the city’s style. luxury miami car rentals [url=https://luxury-car-rental-miami-lxf.com]https://luxury-car-rental-miami-lxf.com[/url] Check the link for the full fleet and pricing for Miami. If you want a luxury car in Miami — just use the link. Luxury car rental Miami — drive in style, arrive with class!
No more settling for basic rentals. I looked at a few different companies before my trip. Then I found a company that had everything I was looking for. luxury car rental miami — From classic luxury sedans to high-performance sports cars. They guided me through the options without any pressure. I chose a car that made the trip unforgettable. This is the company to go with. car rental miami luxury [url=https://luxury-car-rental-miami-mzg.com]https://luxury-car-rental-miami-mzg.com[/url] Save it, share it, don’t lose it for South Florida. If you want a luxury car in Miami — just use the link. Luxury car rental Miami — the ultimate driving experience!
If you desire to increase your familiarity just keep visiting
this web site and be updated with the latest information posted
here.
Miami is a city that demands attention, and your car is part of that statement. I compared reviews, fleets, and prices to find the best option. That’s when I came across the perfect match. exotic car rental miami — Everything from high-end sports cars to elegant luxury sedans. They were professional, friendly, and truly helpful. I took the car out for a spin and it exceeded my expectations. If you’re planning a trip to Miami and want to experience it the right way. rent luxury car miami [url=https://luxury-car-rental-miami-tqk.com]rent luxury car miami[/url] All the details are there for Miami. It’s the easiest way to elevate your trip. Luxury car rental Miami — live the experience!
Miami is the kind of city where your car makes a statement. I started researching luxury car options before my trip. After comparing a few companies, I found the right one. rent a luxury car miami — Everything from sleek European sports cars to American muscle. The service was top-notch. The experience was everything I had hoped for. If you’re visiting Miami and want a car that matches the city’s style. rent luxury car miami [url=https://luxury-car-rental-miami-lxf.com]https://luxury-car-rental-miami-lxf.com[/url] Check the link for the full fleet and pricing for South Beach. It’s the easiest way to make your trip special. Luxury car rental Miami — drive in style, arrive with class!
And for me, that means driving something that matches the vibe. Others were friendly but didn’t have the selection I wanted. Then I found a company that had everything I was looking for. miami luxury car rental — Every car was in pristine condition. The staff was incredibly helpful. I chose a car that made the trip unforgettable. If you’re visiting Miami and want to elevate your experience. high luxury auto rentals miami [url=https://luxury-car-rental-miami-mzg.com]https://luxury-car-rental-miami-mzg.com[/url] Check the link for the full fleet and pricing for South Beach. It’s the easiest way to make your trip unforgettable. Luxury car rental Miami — the ultimate driving experience!
Amma sonra 1xbet tətbiqini yükləməyə qərar verdim və fərqi hiss etdim. Tətbiq daha sürətli, daha rahat və daha sabit işləyir. 1xbet yukle — bir neçə dəqiqəyə yüklənir. Hər şey bir yerdə, rahat və əlçatan. 1xbet tətbiqi ilə mərc etmək daha zövqlüdür. 1xbet indir [url=https://1xbet-yukle-srb.com]1xbet indir[/url] Yükləyin, quraşdırın, başlayın üçün Bakı. 1xbet tətbiqini yükləyib mərclərinizi telefonunuzdan etmək istəyirsinizsə — linkə keçin. 1xbet yüklə — hər zaman, hər yerdə mərc et!
When I decided to visit Miami, I knew I wanted the full experience. Some had good cars but poor service. Then I found a company that had it all. luxury car rental miami — Each car was spotless and ready to hit the road. The staff was professional and welcoming. I took a gorgeous sports car for the weekend. If you want a car that turns heads and delivers excitement. luxury car rentals miami [url=https://luxury-car-rental-miami-jqb.com]luxury car rentals miami[/url] Check the link for the full fleet and pricing for the area. It’s the easiest way to make your trip unforgettable. Luxury car rental Miami — drive the dream!
I wanted my trip to be memorable from the moment I hit the road. I wanted a car that was both stylish and fun to drive. That’s when I came across the perfect match. exotic car rental miami — the cars were incredible. They made sure I got the car that suited my needs perfectly. The car was a major part of why I enjoyed my trip so much. If you want a car that turns heads and delivers excitement. miami luxury car rental [url=https://luxury-car-rental-miami-tqk.com]miami luxury car rental[/url] Save it, share it, don’t lose it for South Florida. It’s the easiest way to elevate your trip. Luxury car rental Miami — live the experience!
Miami is the kind of city where your car makes a statement. I wanted something that would turn heads and make the experience memorable. After comparing a few companies, I found the right one. miami luxury car rental — All the cars looked brand new and well-maintained. No pressure, just honest recommendations. I felt like I was living the Miami dream. This is the place to book. supercar rental miami [url=https://luxury-car-rental-miami-lxf.com]https://luxury-car-rental-miami-lxf.com[/url] Save it, share it, don’t lose it for the area. It’s the easiest way to make your trip special. Luxury car rental Miami — drive in style, arrive with class!
When I think of Miami, I think of style, energy, and luxury. Some had great cars but poor customer service. Then I found a company that had everything I was looking for. exotic car rental miami — From classic luxury sedans to high-performance sports cars. Everything was transparent and professional. Every drive felt like an event. This is the company to go with. luxury car rentals in miami [url=https://luxury-car-rental-miami-mzg.com]luxury car rentals in miami[/url] All the details are there for the area. If you want a luxury car in Miami — just use the link. Luxury car rental Miami — the ultimate driving experience!
Something that matched the energy of the city and made me feel like a star. Some had good cars but poor service. Then I found a company that had it all. rent a luxury car miami — Ferrari, Lamborghini, Rolls-Royce — you name it. The staff was professional and welcoming. I felt like I was living in a movie. This is the company to trust. real car rental [url=https://luxury-car-rental-miami-jqb.com]https://luxury-car-rental-miami-jqb.com[/url] Check the link for the full fleet and pricing for Miami. It’s the easiest way to make your trip unforgettable. Luxury car rental Miami — drive the dream!
I’ve visited a few times before, always with basic rentals. A car that matched the vibrant Miami lifestyle. After comparing a few companies, I found the right one. luxury car rental miami — All the cars looked brand new and well-maintained. No pressure, just honest recommendations. I drove a gorgeous car along the Miami coast. If you’re visiting Miami and want a car that matches the city’s style. luxury cars for rent in miami [url=https://luxury-car-rental-miami-lxf.com]https://luxury-car-rental-miami-lxf.com[/url] All the details are there for the area. It’s the easiest way to make your trip special. Luxury car rental Miami — drive in style, arrive with class!
And for me, that means driving something that matches the vibe. Some had great cars but poor customer service. Then I found a company that had everything I was looking for. exotic car rental miami — From classic luxury sedans to high-performance sports cars. They guided me through the options without any pressure. I got compliments everywhere I went. If you’re visiting Miami and want to elevate your experience. supercar rental miami [url=https://luxury-car-rental-miami-mzg.com]supercar rental miami[/url] All the details are there for Miami. It’s the easiest way to make your trip unforgettable. Luxury car rental Miami — the ultimate driving experience!
But I realized that driving an ordinary rental was holding me back from the full experience. I searched for premium car rental options before my trip. That’s when I found exactly what I was looking for. luxury car rental miami — From sleek sports cars to elegant luxury sedans. The staff was friendly and knowledgeable. Cruising along Ocean Drive with the top down. This is the place to book. supercar rental miami [url=https://luxury-car-rental-miami-hmx.com]supercar rental miami[/url] All the details are there for South Florida. If you want a luxury car in Miami — just use the link. Luxury car rental Miami — drive in style, explore with class!
A regular rental just wouldn’t cut it for this experience. I compared reviews, fleets, and prices to find the best option. That’s when I came across the perfect match. miami luxury car rental — All vehicles were in showroom condition. They made sure I got the car that suited my needs perfectly. The car was a major part of why I enjoyed my trip so much. This is the company to trust. exotic car rental miami [url=https://luxury-car-rental-miami-tqk.com]exotic car rental miami[/url] Check the link for the full fleet and pricing for Miami. It’s the easiest way to elevate your trip. Luxury car rental Miami — live the experience!