How to use mutex in multithreading with C on linux?

Member

by gaston , in category: General Help , 21 days ago

How to use mutex in multithreading with C on linux?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jewel , 20 days ago

@gaston 

To use mutex in multithreading with C on Linux, you can follow these steps:

  1. Include the necessary header files:
1
#include <pthread.h>


  1. Declare a mutex object:
1
pthread_mutex_t mutex;


  1. Initialize the mutex (usually done before creating threads):
1
pthread_mutex_init(&mutex, NULL);


  1. Use the mutex to protect the critical section (code that should only be executed by one thread at a time):
1
2
3
pthread_mutex_lock(&mutex);
// Critical section
pthread_mutex_unlock(&mutex);


The pthread_mutex_lock function acquires the mutex lock, and if it is already locked by another thread, the current thread will be put to sleep until it becomes available. The pthread_mutex_unlock function releases the mutex lock, allowing other threads to acquire it.


Here's a complete example that demonstrates the usage of mutex in multithreading:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mutex;
int counter = 0;

void* threadFunc(void* arg) {
    pthread_mutex_lock(&mutex);
    counter++;
    printf("Thread %ld: Counter = %d
", pthread_self(), counter);
    pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);
}

int main() {
    pthread_t thread1, thread2;

    // Initialize the mutex
    pthread_mutex_init(&mutex, NULL);

    // Create two threads
    pthread_create(&thread1, NULL, threadFunc, NULL);
    pthread_create(&thread2, NULL, threadFunc, NULL);

    // Wait for threads to finish
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    // Destroy the mutex
    pthread_mutex_destroy(&mutex);

    return 0;
}


In this example, two threads are created and both increment the shared counter variable within the critical section protected by the mutex. The output will show that the counter is incremented sequentially by each thread, avoiding any race conditions.


Remember to compile your program with the -lpthread flag to link against the pthread library:

1
gcc -o program program.c -lpthread