Loading W Code...
Deep Dive into Threads, CPU Scheduling, Semaphores & Deadlocks
The kernel maintains a PCB data structure for every active process:
PID & PPID (Process & Parent IDs)PC) & Register State// C Multithreading vs Process Creation Example
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void* thread_function(void* arg) {
printf("Executing Thread within PID: %d
", getpid());
return NULL;
}
int main() {
pid_t pid = fork(); // Creates child process (Separate PID & Memory)
if (pid == 0) {
pthread_t tid;
pthread_create(&tid, NULL, thread_function, NULL); // Creates Thread
pthread_join(tid, NULL);
}
return 0;
}The CPU Scheduler selects ready queue processes for CPU execution using specific performance goals (Minimizing Waiting Time & Maximizing Throughput):
# Simulator metrics calculation for Round Robin
def calculate_turnaround_and_waiting(arrival_times, burst_times, quantum):
# MLFQ / RR Scheduling Metric Evaluator
passWhen concurrent threads read and write shared memory, a Race Condition can corrupt data structures unless synchronized.
lock(), unlock()).wait() / P(), signal() / V()) regulating access to $N$ identical shared resources.// POSIX Mutex Synchronization Example
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int shared_counter = 0;
void* increment_counter(void* arg) {
pthread_mutex_lock(&lock);
// Critical Section
shared_counter++;
pthread_mutex_unlock(&lock);
return NULL;
}A Deadlock is a frozen state where two or more processes cannot make progress because each holds a resource requested by another.
// Banker's Algorithm Safety Check Pseudocode
// Need[i][j] = Max[i][j] - Allocation[i][j]
bool isSafeState(int Work[], bool Finish[], int Alloc[][R], int Need[][R]) {
// Computes safe execution sequence if Available >= Need
return true;
}Since processes run in isolated address spaces, they communicate via explicit kernel-provided IPC channels:
shmget, mmap): Maps physical memory frames into multiple virtual address spaces (Fastest IPC, requires mutexes).# C Pipe IPC Example
int pipefds[2];
char buffer[30];
pipe(pipefds);
if (fork() == 0) {
// Child Process: Write to Pipe
write(pipefds[1], "IPC Communication", 17);
} else {
// Parent Process: Read from Pipe
read(pipefds[0], buffer, 17);
}