Multithreading in C allows you to execute multiple parts of a program concurrently. This tutorial focuses on how to use POSIX threads (pthreads) to manage multiple threads in your C programs.
C Multithreading Tutorial
1. Introduction to Multithreading
Multithreading enables your program to perform tasks in parallel, potentially improving performance and responsiveness. In C, the POSIX thread library (pthreads) is commonly used for multithreading.
2. Creating a Thread
To create a thread in C, we use the `pthread_create` function. This function allows you to specify the function the thread should execute.
#include <stdio.h>
#include <pthread.h>
void* print_message(void* msg) {
printf("%s\n", (char*)msg);
return NULL;
}
int main() {
pthread_t thread;
const char* message = "Hello from the thread!";
pthread_create(&thread, NULL, print_message, (void*)message);
pthread_join(thread, NULL);
return 0;
}
This code demonstrates how to create a thread that prints a message. The `pthread_create` function starts a new thread, and `pthread_join` waits for the thread to finish before the program exits.
3. Synchronization with Mutexes
In multithreading, when multiple threads access shared resources, synchronization is important to prevent race conditions. Mutexes are used to ensure that only one thread can access a shared resource at a time.
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t lock;
void* increment_counter(void* counter) {
pthread_mutex_lock(&lock);
int* cnt = (int*)counter;
(*cnt)++;
pthread_mutex_unlock(&lock);
return NULL;
}
int main() {
pthread_t thread1, thread2;
int counter = 0;
pthread_mutex_init(&lock, NULL);
pthread_create(&thread1, NULL, increment_counter, &counter);
pthread_create(&thread2, NULL, increment_counter, &counter);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Counter value: %d\n", counter);
pthread_mutex_destroy(&lock);
return 0;
}
In this example, two threads increment a shared counter. A mutex is used to synchronize access to the counter, ensuring that only one thread can modify it at a time.
4. Conclusion
Multithreading in C can greatly improve the performance and efficiency of your programs, especially when handling multiple tasks concurrently. By using pthreads, you can easily create and manage threads, and employ synchronization techniques like mutexes to avoid race conditions.