Implement a cooperative task scheduler in C from scratch without FreeRTOS. Maintain a linked list of function pointers as tasks and write a yield() function that saves CPU context to a custom stack and switches to the next task.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is an interesting request to build a cooperative task scheduler in C from scratch without using FreeRTOS. Let me think through what we need:
A task structure that holds:
Function pointer to the task code
Stack pointer and stack memory
Context (registers, program counter, etc.)
Status (running, blocked, etc.)
Linked list pointers
Context switching mechanism:
Save current CPU context (registers, stack pointer)
Restore next task's context
This is generally platform-specific (x86, ARM, etc.)
A yield() function that:
Saves the current task's context
Switches to the next task in the linked list
Restores its context
Task management:
Create tasks
Add them to the scheduler
Remove/delete tasks
Initialize the scheduler
I'll implement this for a generic platform, but I'll focus on x86-64 and also provide comments for ARM. For the context switching, I'll need to use inline assembly or external assembly code.
Let me create a comprehensive implementation:
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define STACK_SIZE 4096
#define MAX_TASKS 10
// Task control block
typedef struct Task {
uint8_t *stack; // Stack memory
uint8_t *stack_ptr; // Current stack pointer
uint32_t stack_size; // Stack size
void (*func)(void); // Task function
int id; // Task ID
int status; // 0 = ready, 1 = running
struct Task *next; // Next task in linked list
struct Task *prev; // Previous task
} Task;
// CPU context structure
typedef struct {
uint64_t r15;
uint64_t r14;
uint64_t r13;
uint64_t r12;
uint64_t rbx;
uint64_t rbp;
uint64_t rsi;
uint64_t rdi;
uint64_t rax;
uint64_t rcx;
uint64_t rdx;
uint64_t rsp;
uint64_t rip;
} Context;
// Global scheduler state
typedef struct {
Task *head;
Task *current;
Task *tail;
int task_count;
int next_id;
} Scheduler;
I need to define the CPU context structure to capture all the x86-64 registers that need to be preserved during a context switch, then set up the scheduler state to track the task queue and maintain the current executing task.
The task creation function allocates memory for both the task structure and its stack, then initializes the context by setting the instruction pointer to the task function and positioning the stack and base pointers appropriately. When adding tasks to the scheduler, I need to handle the case where the queue is empty by setting the head, and otherwise append to the tail while maintaining the linked list structure. itasking)
void yield(void) {
if (scheduler.task_count == 0) return;
// Run scheduler
void scheduler_run(void) {
if (scheduler.
The yield function moves to the next task in the circular queue and performs a context switch. Task deletion removes the task from the scheduler, frees its allocated stack memory, and deallocates the task structure itself. The scheduler initialization sets all pointers to null and resets the task counter and ID generator. The scheduler_run function begins execution but appears incomplete. _create(task3, STACK_SIZE);
I'm realizing that a complete context switching implementation needs actual assembly code for proper register and stack management. I should provide a practical approach using either setjmp/longjmp for portability, or platform-specific assembly for x86-64 and ARM architectures.
Let me create a compilable solution that combines setjmp/longjmp as the core mechanism with inline assembly options for more control. I'll structure it with a Task struct that tracks execution state, stack allocation, and task status through a ready/running/blocked lifecycle.
The scheduler maintains a linked list of tasks with a current pointer to track which one is executing. Each task gets its own allocated stack and a jmp_buf to save/restore its execution context. When creating a new task, I allocate memory for both the Task structure and its stack, initialize the task ID from a counter, and set its initial status to ready.
Adding a task to the scheduler inserts it into a circular doubly-linked list. If it's the first task, it points to itself; otherwise, it gets linked at the tail while maintaining the circular structure. The yield function saves the current task's context and switches to the next task in the queue, restoring its saved state to resume execution. task->status == 2 ? "Blocked" : "Ready");
task = task->next;
}
printf("Current task: %d\n", sched.current ? sched.current->id : -1);
}
void task_a(void) {
for (int i = 0; i < 3; i++) {
printf("Task A: step %d\n", i);
yield();
}
printf("Task A: completed\n");
}
void task_b(void) {
for (int i = 0; i < 3; i++) {
printf("Task B: step %d\n", i);
yield();
}
printf("Task B: completed\n");
}
void task_c(void) {
for (int i = 0; i < 3; i++) {
printf("Task C: step %d\n", i);
yield();
}
printf("Task C: completed\n");
}
The setjmp/longjmp mechanism won't work well for this execution model. For cooperative multitasking to function properly, I need to preserve each task's execution state when it yields, then restore it when the scheduler switches back to that task. The core challenge is managing context switches—saving where we are in one task and jumping to where another task left off.
A state machine approach using setjmp/longjmp can handle this if structured carefully, though inline assembly offers more direct control. I'll build an implementation that properly manages the task queue, tracks task states, and demonstrates context switching with a checkpoint system to track where each task paused.
The core structure uses a doubly-linked task queue where each task stores its execution environment. When creating a task, I allocate memory for both the task metadata and its stack, initializing the state to TASK_READY. The scheduler maintains pointers to the head, tail, and current running task, along with a counter and ID generator. During initialization, these are zeroed out and a flag marks the scheduler as ready. Adding tasks to the queue involves appending them to the linked list while incrementing the task count. The yield function logs the context switch, then uses setjmp to save the current task's execution state. If setjmp returns 0, we're in the saving phase, so we update the scheduler to point to the next task and use longjmp to restore its context. When longjmp returns us here later, we simply resume execution. The task_exit function marks the current task as finished and logs it, preparing for cleanup.
If there are remaining tasks in the queue, we move the scheduler's current pointer to the next task and jump to its saved context to resume execution. The scheduler_print_status function displays a summary of all tasks, iterating through the linked list and showing each task's ID, state (READY, RUNNING, BLOCKED, or FINISHED), and whether it's currently executing.
The scheduler_run function initializes execution by setting up the first task's context with setjmp and marking it as RUNNING before calling its function. The example tasks demonstrate the pattern: each one prints status messages, loops through iterations while yielding control back to the scheduler, then signals completion. The main function begins setting up the cooperative multitasking system.
I'm realizing setjmp/longjmp has a fundamental limitation here—once you return from the function where setjmp was called, the saved context becomes invalid, so this approach won't actually enable proper task switching.
I need to implement real context switching using inline assembly instead. Let me build this properly with architecture-specific code that can actually save and restore execution state across function boundaries.
Cooperative Task Scheduler in C from Scratch
I'll provide a complete implementation with context switching via inline assembly and proper stack management.
Complete Implementation
c
Compilation
bash
# For x86-64 Linux/Unix
gcc -O2 -fno-stack-protector -march=native -o scheduler scheduler.c
# For ARM (Cortex-M)
arm-none-eabi-gcc -O2 -mcpu=cortex-m4 -o scheduler scheduler.c
# With debugging
gcc -g -O0 -fno-stack-protector -o scheduler scheduler.c