Creating threads with pthread_create
What you'll learn: How to use the pthread_create function to launch a new line of execution that runs parallel to your main program.
The multi-lane highway
By default, a C program is like a single-lane road. Code executes one line at a time, in order. If one task takes a long time, everything behind it has to wait. Multithreading turns that road into a multi-lane highway. Using the pthread library, you can spawn a "worker" thread to handle a specific task in another lane while your main program keeps moving.
How to spawn a thread
To create a thread, we use the pthread_create function. It requires four ingredients:
- The ID: A variable of type
pthread_tto act as the thread's "name tag." - Attributes: Settings for the thread (usually
NULLfor default). - The Function: The name of the function you want the thread to run.
- The Argument: Any data you want to pass to that function (or
NULL).
The function you want to run must have a specific signature: it must return void * and take exactly one void * argument. Think of void * as a "universal plug" that can point to any data type.
A simple example
Here is how you launch a thread to say hello while the main program continues its work.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// This is the task our thread will perform
void* print_message(void* arg) {
char* message = (char*)arg;
printf("Thread says: %s\n", message);
return NULL;
}
int main() {
pthread_t thread_id;
char* msg = "Hello from the new lane!";
// 1. Thread ID, 2. Attributes, 3. Function, 4. Argument
pthread_create(&thread_id, NULL, print_message, (void*)msg);
printf("Main program is still running in its own lane...\n");
// Wait for the thread to finish before exiting
pthread_join(thread_id, NULL);
return 0;
}
Why it matters
When you call pthread_create, the function doesn't wait for the thread to finish. It returns almost instantly, and the two parts of your code run at the same time. This is the foundation of high-performance software, allowing apps to stay responsive while performing heavy calculations or waiting for internet downloads in the background.
Key takeaway
Use pthread_create to delegate a specific function to a new thread, allowing your program to perform multiple tasks simultaneously.