惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Attack and Defense Labs
Attack and Defense Labs
Y
Y Combinator Blog
阮一峰的网络日志
阮一峰的网络日志
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
V
Visual Studio Blog
量子位
博客园 - 三生石上(FineUI控件)
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Jina AI
Jina AI
宝玉的分享
宝玉的分享
Hacker News: Ask HN
Hacker News: Ask HN
小众软件
小众软件
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Hacker News - Newest:
Hacker News - Newest: "LLM"
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Google Online Security Blog
Google Online Security Blog
AI
AI
Schneier on Security
Schneier on Security
大猫的无限游戏
大猫的无限游戏
WordPress大学
WordPress大学
I
InfoQ
A
Arctic Wolf
月光博客
月光博客
Last Week in AI
Last Week in AI
Hugging Face - Blog
Hugging Face - Blog
Cloudbric
Cloudbric
Google DeepMind News
Google DeepMind News
Security Latest
Security Latest
GbyAI
GbyAI
N
Netflix TechBlog - Medium
TaoSecurity Blog
TaoSecurity Blog
Blog — PlanetScale
Blog — PlanetScale
Scott Helme
Scott Helme
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
The Exploit Database - CXSecurity.com
博客园 - 【当耐特】
博客园 - 司徒正美
The Hacker News
The Hacker News
Cisco Talos Blog
Cisco Talos Blog
I
Intezer
云风的 BLOG
云风的 BLOG
T
Threatpost
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
罗磊的独立博客
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Tenable Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
I Implemented MLFQ in C and here's how I did It
N Satyadev · 2026-05-26 · via DEV Community

Enough with the unga bunga puny algorithms.. did you know there exists an
scheduling algorithm that literally paved way for modern technology? and no it is not yet another FCFS where people just throw jobs in array order and call it a day without even bothering to sort...
What I am referring to is MLFQ (Multi Level Feedback Queue). Now a FCFS is fine.. it's like print("hello world") of OS scheduling but clearly we don't wanna "hello" the world forever.. there are in fact unhealthy amount of reasons why MLFQ is considered one of the greatest algorithms.. it outperforms every previous algorithm to exist..

  • FCFS: just runs in arrival order
  • SRTF: very dangerous as it is prone to starvation (gfg link to starvation article)
  • RR: well... RR is just RR.. Equality is overrated in 2026 anyway, so we don't really care about it much.

These are all valid reasons but there's another massive reason that is common to all.. if you notice any algorithm before MLFQ demands a prerequisite number i.e. it's burst time... sure RR does not require it, but RR believes in equal quantum time... which honestly works but MLFQ is RR on steroids which is much better.

RR operates on a single queue. Job runs for certain quantum time then next one runs and so on until there's no active process left..

That clearly takes care of the scheduling but do you see why it is not so efficient? Imagine yourself in a supermarket, all you want are some
hot cheetos.. but grandma amy, Infront of you is buying half the store cuz she got 27 coupons. Now you gotta wait for 30 whole mins just to get your cheetos.. the point is, that is pretty inefficient. Not that it won't get the job done but why wait so long for something so insignificant? that is whole point of MLFQ..

In this blog/article/my rant from now we're gonna get into deep dive discussion on MLFQ including a working C code walk through.

Now comes the juicy part.. the actual C code on how to go about it..

IMPLEMENTATION

Stage 1: The Structure

Job Structure

struct Job {
int arrival_time;
int cpu_burst;
int start;
int end;
int turnaround;
int response;
int remaining_time;
bool inQueue;
int serial;
int alloted_time;
int alloted_left;
};

Node Structure

struct Node {
int data;
struct Node *next;
};

Stage 2: The Implementation

So, the structure we go ahead from now is list the rule and I show
how I implemented it in code

Rule 1: If a process has a higher priority (higher queue), it runs first. If the priorities are equal, the process runs in round-robin fashion.

if (head != NULL) {
currentNode = head;
activeHead = &head;
activeTail = &tail;
} else if (head2 != NULL) {
currentNode = head2;
activeHead = &head2;
activeTail = &tail2;
}

The above has some terms like activeHead and activeTail which you can ignore for now as they are a very special segment which i will discuss later but here what's important is the RULE that is applies... at present the rule says highest priority runs and lower one doesnt... here let say there are only 2 queues.. so we check if head which is the root of that queue(a linked list) is empty or not.. if it is then clearly no jobs are running on high priority so we go for second queue which is head2 in this case.. so now head2 is checked and jobs in there are ran.
But what about next part which is if same priority then jobs run in RR fashion? the next piece of code does exactly that.

(*activeHead) = currentNode->next;
currentNode->next = NULL;
(*activeTail)->next = currentNode;
(*activeTail) = currentNode;

Here activeHead indicates which head is active btw(wow! totally genius). all RR does is get the first job and attach it at the back after quantum time.. that way rotation happens and fairness is imposed.

Rule 2: If a process exhausts its allocated time slice in a higher priority queue, it is demoted to a lower priority queue.

else if (job->alloted_left <= 0) {

Now if a job has alot of processing to do it will clearly take alot of time just like grandma amy and we all hate waiting.. hence MLFQ _gracefully _handles the situation by introducing concept of alloted time as mentioned earlier.

First we check "did the job use all of it's alloted time?" if yes then it has to go to counter two which only works after counter 1(queue1) is empty hence maintaining priority.

if (currentNode == head) {
temp = head;
head = head->next;
temp->next = NULL;
if (tail2 == NULL)
head2 = tail2 = currentNode;
else {
tail2->next = temp;
tail2 = temp;
temp = NULL;
}
}

then for our code we must check whether 2nd queue is empty or it already got someone else waiting.. if it's empty we just do head2 = tail2 = currentNode; which says hey, since there's no job in this queue point the head and tail of this to currentNode which is well.. the current node. But if it is not empty then we make the poor guy to go back to waiting by appending to end which we can see with this piece of code

tail2->next = temp;
tail2 = temp;
temp = NULL;

finally after we shift lower priority queue we would again want it to get it's alloted time as punishing the job forever just because it takes alot of time isn't fair.. so we do something like job->alloted_left = job->alloted_time; which resets the alloted timer and the job again get back to action (in lower priority)

Rule 3: After a fixed reset interval, all processes are boosted back to the highest priority queue.

if (reset_timer == 0) {
clearQueue(&head, &tail, &head2, &tail2, reset);
enqueueReset(jobs, &head, &tail, len);
reset_timer = reset;
}

Reset timer is another feature which makes MLFQ OP.. it not only treats the poor(you with hot cheetos) fairly but also the wealthy(grandma amy.. technically). It introduces reset which is a timer when it resets the whole system. By reset i mean taking all the jobs back to higher priority so that all get equal chance again avoiding starvation again.

This shows a clear queue function which is an approach that i used for reset. basically this is divided in 3 parts.

if (*head2 == NULL) return;

if 2nd queue is empty.. well just return as no need to reset since whole point of reset is get all stuff from queue2 to queue1.

if (*head == NULL) {
*head = *head2;
*tail = *tail2;
}

If head itself is null then head2(head of 2nd queue) is only active.. so we just map the 1st queue to 2nd and that's.

else {
(*tail)->next = *head2;
*tail = *tail2;
}

Finally if head2 is not null and head is also not null then just make the tail(last node of 1st queue) point to head2(first node of queue2) and make the tail of Q1 same as Q2.. Viola.. Now we have a single Q1 which has all current jobs.

Now we also need to insert new jobs available as we cannot leave any job unattended hence following can be done.

What the code does here is parse the entire array containing jobs, check whether it is still in queue and has not ended yet which indicates job is not finished yet. if found we make a new node out of it.

if(!(*head)) {
*head = *tail = newNode;
} else {
(*tail)->next = newNode;
*tail = newNode;
}

Then we check if head empty? if yes then there no active jobs and this new one is the highest priority if not then we just append the new job at tail of **FIRST **Queue not 2nd because new jobs are always assigned highest priority.

Now the an interesting approach here is use of double pointers a double pointer is as name suggests pointer to a pointer.

struct Node **activeHead, **activeTail;

What this does is declare a variable that points to something that is pointing to something else.. like activeHead -> head -> Node

essentially is like a of a train. Hypothetically let say there are only 3 compartments in a train. The engine which drives everything is a actual Node. 2nd compartment is connected to engine and 3rd is connected to 2nd.. similarly head -> Node and activeHead -> head.

Now how does this help in this scenario?

MLFQ is not restricted to only 2 Queues but more than 2 which makes it even more efficient. This double pointer helps avoid a huge if else statement by using activeHead, we write the scheduling logic once. We point activeHead to whichever queue has jobs, and the code treats it the same way whether it’s Queue 1, Queue 2, or Queue 10. It’s polymorphism for C programmers.

If you see it can get pretty ugly real fast. For more Queue's the if else string gets extended further which makes the code complete trash and stinky.

Now it leads us back to the snippet shared in the very first rule. This way we set the activeHead and activeTail by checking whether head is empty or not.

Conclusion

And that pretty much wraps up my implementation of MLFQ. What initially looked like “just another scheduling algorithm” ended up being one of the most interesting systems I’ve implemented so far.
Anyways if you actually read till here, congratulations. You survived queues, starvation, double pointers and my terrible supermarket analogies.