How to use mutex in multithreading with C on linux?

Member

by gaston , in category: General Help , 7 months ago

How to use mutex in multithreading with C on linux?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by jewel , 7 months 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


by emerald.wunsch , 2 months ago

@gaston 

Here is an example code that demonstrates the usage of mutex in multithreading with C on Linux:

 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
#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mutex;
int shared_variable = 0;

void* thread_func(void* arg) {
    pthread_mutex_lock(&mutex);
    
    for (int i = 0; i < 5; i++) {
        shared_variable++;
        printf("Thread %lu - Shared Variable: %d
", pthread_self(), shared_variable);
    }
    
    pthread_mutex_unlock(&mutex);
    pthread_exit(NULL);
}

int main() {
    pthread_t thread1, thread2;

    pthread_mutex_init(&mutex, NULL);

    pthread_create(&thread1, NULL, thread_func, NULL);
    pthread_create(&thread2, NULL, thread_func, NULL);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    pthread_mutex_destroy(&mutex);

    return 0;
}


In this code:

  • We define a shared_variable that will be incremented by two threads (thread1 and thread2) within the critical section protected by the mutex.
  • The thread_func function increments the shared_variable in a loop, displaying the thread ID and the current value of the variable.
  • In the main function, we create two threads, each executing the thread_func.
  • We use mutex to protect the critical section where the shared_variable is incremented.
  • Finally, we initialize, join, and destroy the mutex.


Compile the program using the pthread library:

1
gcc -o program program.c -lpthread


When you run the program, you should see the output where each thread increments the shared_variable sequentially due to mutex locking and unlocking. The output may vary due to the nature of parallel execution.


Remember to handle errors while using mutexes for proper multithreading synchronization.