c:pthreads:mutex-shared-variable
Using mutex in pthread to access a shared variable
- pthread-mutex-shared-var.c
#include <stdio.h> #include <stdlib.h> #include <pthread.h> // Global variable and mutex int shared_variable = 0; pthread_mutex_t mutex; // Function to be executed by threads void *update_shared_variable(void *arg) { pthread_mutex_lock(&mutex); // Lock the access to the variable shared_variable++; // Update the shared variable printf("Updated value: %d\n", shared_variable); pthread_mutex_unlock(&mutex); // Unlock the access to the variable pthread_exit(NULL); } int main() { pthread_t thread1, thread2; // Initialize the mutex pthread_mutex_init(&mutex, NULL); // Create the threads pthread_create(&thread1, NULL, update_shared_variable, NULL); pthread_create(&thread2, NULL, update_shared_variable, NULL); // Wait for the threads to finish pthread_join(thread1, NULL); pthread_join(thread2, NULL); // Destroy the mutex pthread_mutex_destroy(&mutex); return 0; }
The program demonstrates the use of a mutex to synchronize access to a shared variable between multiple threads.
It uses pthreads for creating threads and a mutex to ensure that only one thread can access and modify the shared variable at a time.
Global Variable and Mutex: A global integer shared_variable and a mutex mutex are defined.
Thread Function: update_shared_variable locks the mutex before accessing the shared variable, increments it, prints the updated value, and then unlocks the mutex.
Main Function: Initializes the mutex, creates two threads that run update_shared_variable, waits for these threads to complete, and finally destroys the mutex.
c/pthreads/mutex-shared-variable.txt · Last modified: 2024/01/17 00:05 by odefta