Skip to main content

Multithreading in C

Multithreading in C refers to the ability of a program to run multiple threads (independent units of execution) concurrently within a single process. This means that different parts of the program can be executed simultaneously on different threads, potentially increasing efficiency and improving the program's responsiveness. Multithreading in C can be used to perform parallel processing, where multiple threads work together to complete a task faster than a single thread could. However, multithreading can also introduce synchronization issues and requires careful management of shared resources to ensure thread safety.

Example for two threads execute synchronously

#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mutex;
pthread_cond_t cond_var;
int count = 0;

void *thread_function(void *arg) {
    int i;
    int thread_num = *((int*)arg);
    for (i = 0; i < 10; i++) {
        pthread_mutex_lock(&mutex);
        while (count != thread_num - 1) {
            pthread_cond_wait(&cond_var, &mutex);
        }
        printf("Thread %d: %d\n", thread_num, i);
        count = (count + 1) % 2;
        pthread_cond_broadcast(&cond_var);
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main() {
    pthread_t thread1, thread2;
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond_var, NULL);
    int arg1 = 1, arg2 = 2;
    pthread_create(&thread1, NULL, thread_function, &arg1);
    pthread_create(&thread2, NULL, thread_function, &arg2);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond_var);
    return 0;
}

To fix this error, you need to add the -pthread flag to your compile command. For example:

// Compile
gcc myprogram.c -o myprogram -pthread

// Run
./myprogram.out

Output

Thread 1: 0
Thread 2: 0
Thread 1: 1
Thread 2: 1
Thread 1: 2
Thread 2: 2
Thread 1: 3
Thread 2: 3
Thread 1: 4
Thread 2: 4
Thread 1: 5
Thread 2: 5
Thread 1: 6
Thread 2: 6
Thread 1: 7
Thread 2: 7
Thread 1: 8
Thread 2: 8
Thread 1: 9
Thread 2: 9

Simultaneously Multithreading example

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define NUM_THREADS 4

void *thread_func(void *arg) {
    int thread_num = *((int*)arg);
    printf("Thread %d started\n", thread_num);
    // do some work here...
    printf("Thread %d finished\n", thread_num);
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[NUM_THREADS];
    int thread_args[NUM_THREADS];
    int i, rc;
    
    // create the threads
    for (i = 0; i < NUM_THREADS; i++) {
        thread_args[i] = i;
        rc = pthread_create(&threads[i], NULL, thread_func, (void *)&thread_args[i]);
        if (rc) {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(EXIT_FAILURE);
        }
    }
    
    // wait for the threads to finish
    for (i = 0; i < NUM_THREADS; i++) {
        rc = pthread_join(threads[i], NULL);
        if (rc) {
            printf("ERROR; return code from pthread_join() is %d\n", rc);
            exit(EXIT_FAILURE);
        }
    }
    
    printf("All threads finished\n");
    return 0;
}

In this example, we define a function called thread_func that takes a void pointer as an argument. This function is the entry point for each thread, and it will be executed concurrently.

In the main function, we create NUM_THREADS threads using a for loop. For each thread, we create a new thread identifier (pthread_t) and pass it to pthread_create(), along with a pointer to the thread function (thread_func) and an argument that we want to pass to the thread (in this case, the thread number).

After creating all the threads, we use another for loop to wait for them to finish using pthread_join(). This function blocks the calling thread until the specified thread has terminated, so we can ensure that all the threads have finished before continuing.

Output

Thread 1 started
Thread 1 finished
Thread 2 started
Thread 2 finished
Thread 0 started
Thread 0 finished
Thread 3 started
Thread 3 finished
All threads finished




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment