🔒

Mutex Lock for Thread Synchronization

Nov 27, 2024

Mutex Lock for Linux Thread Synchronization

Introduction

  • Thread synchronization: Ensures that concurrent threads do not execute a critical section simultaneously.
  • Critical section: A segment of code that accesses shared resources.
  • Race condition: Occurs when threads access shared resources without proper synchronization, leading to unpredictable results.

Synchronization Problem Example

  • Sample C program demonstrates synchronization issues using threads.
  • Code Structure:
    • Two threads are created.
    • Each thread runs a function that increments a counter and prints job start/finish logs.
    • Compilation: Use gcc filename.c -lpthread to link the pthreads library.

Observed Output

  • "Job 2 has finished" is printed twice; "Job 1 has finished" is missing.
  • Issue: Lack of synchronization causes incorrect counter values due to concurrent thread execution.

Solution: Using Mutexes

  • Mutex: A locking mechanism to enforce exclusive access to a shared resource.
  • Ensures that only one thread can execute a critical section at any time.

Mutex Functionality

  • If a thread locks a code section with a mutex, other threads are blocked until the lock is released.
  • Mutex lock and unlock functions:
    • pthread_mutex_init(): Initializes a mutex.
    • pthread_mutex_lock(): Locks a mutex; blocks if already locked.
    • pthread_mutex_unlock(): Unlocks a mutex; notifies waiting threads.
    • pthread_mutex_destroy(): Destroys a mutex.

Example with Mutex

  • Modified code with mutex to achieve thread synchronization:
    • Mutex is initialized in main.
    • Mutex is locked in trythis() before accessing the shared resource.
    • Mutex is unlocked at the end of trythis().
    • Mutex is destroyed in main after threads complete.

Correct Output

  • "Job 1 started", "Job 1 finished", "Job 2 started", "Job 2 finished".
  • Proper synchronization achieved using mutex.

References

  • Lock and synchronization concepts in computer science.

Additional Information

  • Advanced topics on thread synchronization and Linux commands available in related articles.