how to mutex lock in c

To use mutex locks in C, you can follow these steps:

  1. Include the necessary header file: pthread.h

  2. Declare a mutex variable: pthread_mutex_t mutex;

  3. Initialize the mutex variable: pthread_mutex_init(&mutex, NULL);

  4. Lock the mutex before accessing the critical section: pthread_mutex_lock(&mutex);

  5. Perform the operations that need to be protected by the mutex.

  6. Unlock the mutex after finishing the critical section: pthread_mutex_unlock(&mutex);

  7. Destroy the mutex when it is no longer needed: pthread_mutex_destroy(&mutex);

Here is an example code snippet that demonstrates the usage of mutex locks in C:

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

pthread_mutex_t mutex;

void threadFunction(void arg) {
    // Lock the mutex
    pthread_mutex_lock(&mutex);

    // Critical section
    printf("Thread %d is in the critical section.\n", (int)arg);

    // Unlock the mutex
    pthread_mutex_unlock(&mutex);

    return NULL;
}

int main() {
    pthread_t thread1, thread2;
    int threadId1 = 1, threadId2 = 2;

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

    // Create the threads
    pthread_create(&thread1, NULL, threadFunction, &threadId1);
    pthread_create(&thread2, NULL, threadFunction, &threadId2);

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

    // Destroy the mutex
    pthread_mutex_destroy(&mutex);

    return 0;
}

This code creates two threads that execute the threadFunction, which represents the critical section. The mutex lock is used to ensure that only one thread can access the critical section at a time.

Please note that the code provided is a basic example, and you may need to adapt it to your specific requirements.