The C language is probably one of the best creations of mankind. C is legendary for its speed and raw memory control. But out of the box, standard C executes linearly—one instruction at a time. So, what happens when you want your program to do two things at once?
Here, multithreading comes into play. Multithreading allows a single process to execute multiple threads concurrently. Think of it like a restaurant kitchen: instead of one chef doing the chopping, cooking, and plating sequentially, you hire three chefs to do these tasks at the same time. The result? Much faster service.
In the C ecosystem, especially on Unix-like operating systems (Linux, macOS), the gold standard for multithreading is the POSIX threads library, commonly known as pthreads.
Here is a quick guide to getting your first multithreaded C program up and running.
The Essential Functions
To write a basic multithreaded program, you only need to understand two primary functions from the <pthread.h> library:
pthread_create()This spawns a new thread and tells it which function to execute.pthread_join()This forces the main program to wait until the thread has finished its job before moving on. Without this, your main program might finish and exit before your thread even gets a chance to run!
Now, let's put this into practice with raw C code.
The Code: Your First Thread
Let's look at a minimal, complete example. We will write a script that creates a thread that runs a custom function, and the main program will wait for the thread to finish.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h> // For the sleep() function
// This is the function that our thread will execute.
// It must return void* and take a void* argument.
void *customThreadFunction(void *vargp) {
printf("--> Thread: I am running concurrently!\n");
sleep(2); // Simulate some time-consuming work
printf("--> Thread: My work is done.\n");
return NULL;
}
int main() {
pthread_t thread_id;
printf("Main: Starting the program...\n");
// 1. Create the thread
// Arguments: thread ID reference, attributes (NULL = default), function to run, function arguments
if (pthread_create(&thread_id, NULL, customThreadFunction, NULL) != 0) {
printf("Main: Failed to create thread\n");
return 1;
}
printf("Main: Thread created! Waiting for it to finish...\n");
// 2. Wait for the thread to finish
pthread_join(thread_id, NULL);
printf("Main: Thread joined. Exiting program.\n");
return 0;
}The Output
When you run the compiled program you will see the execution flow bouncing between the main process and your newly created thread:
Main: Starting the program...
Main: Thread created! Waiting for it to finish...
--> Thread: I am running concurrently!
[... 2 second pause ...]
--> Thread: My work is done.
Main: Thread joined. Exiting program.We'll learn more on multithreading in the future. Until then, keep coding!