Multi-threading is the ability of a program to perform multiple tasks concurrently. In C, multi-threading is implemented using the pthread library, which provides functions and structures for creating, synchronizing, and managing threads.
The pthread library defines a thread as a separate flow of execution within a process. Each thread has its own stack and program counter, but shares the same memory space as other threads in the same process. This allows threads to access and modify the same data, which can be both an advantage and a source of synchronization issues.
To use the pthread library in C, you need to include the <pthread.h> header file and link against the pthread library using the -lpthread option. Here is an example program that creates two threads that print messages to the console:
#include <stdio.h>
#include <pthread.h>
void *thread_function(void *arg) {
char *message = (char *)arg;
printf("%sn", message);
return NULL;
}
int main() {
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int ret1, ret2;
ret1 = pthread_create(&thread1, NULL, thread_function, (void *)message1);
ret2 = pthread_create(&thread2, NULL, thread_function, (void *)message2);
if (ret1 != 0 || ret2 != 0) {
printf("Error creating threads.n");
return 1;
}
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
In this example, the main() function creates two threads using the pthread_create() function. Each thread runs the same function, thread_function(), which takes a single argument of type void *. The argument is cast to a char * and printed to the console. Finally, the main() function waits for the threads to complete using the pthread_join() function.
One of the challenges of multi-threading in C is synchronizing access to shared data between threads. This can be done using synchronization primitives such as mutexes, semaphores, and condition variables, which are also provided by the pthread library.