Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Advanced C: Multithreading Intro

Lesson 46 of 53 in the free Foundation of C & C++ notes on Siksha Sarovar, written by Rohit Jangra.

Doing Two Things at Once

By default, a C program is Single-Threaded. It executes one line of code at a time. In the modern world of 8-core and 16-core CPUs, this is a waste of power!

What is a Thread?

A thread is a "lightweight process." You can have multiple threads running inside one program, all sharing the same memory.

POSIX Threads (pthreads)

On Linux and Mac, we use the <pthread.h> library.

  • pthread_create: Spawns a new thread to run a specific function.
  • pthread_join: Waits for a thread to finish.

Why is it hard?

Race Conditions: When two threads try to change the same variable at the exact same time. The result is unpredictable and causes "Heisenbugs" (bugs that disappear when you try to find them).

Synchronization (The Solution)

To keep threads safe, we use:

  1. Mutex (Mutual Exclusion): Like a key to a bathroom. Only the thread with the key can enter the "critical section" and change a variable.
  2. Semaphores: Signals used to coordinate complex tasks.
Multithreading is one of the most difficult topics in computer science. It requires a completely different way of thinking. Master the basics of C first before trying to build a multi-threaded web server!