# mutex

***

**1. Thread Synchronization for Critical Sections**

```cpp
class CriticalSection {
private:
    std::mutex mtx; // Mutex to protect critical section

public:
    void lock() { mtx.lock(); }
    void unlock() { mtx.unlock(); }
};

int main() {
    CriticalSection cs;
    // Acquire lock
    cs.lock();
    // Access shared resource within critical section
    // Release lock
    cs.unlock();
}
```

**2. Producer-Consumer Queue**

```cpp
class Queue {
private:
    std::mutex mtx; // Mutex to protect shared queue
    std::queue<int> q;

public:
    void produce(int item) {
        std::lock_guard<std::mutex> lock(mtx);
        q.push(item);
    }

    int consume() {
        std::lock_guard<std::mutex> lock(mtx);
        if (q.empty()) {
            return -1; // Queue is empty, return error code
        }
        int item = q.front();
        q.pop();
        return item;
    }
};
```

**3. Race Condition Prevention in Multithreaded I/O**

```cpp
std::mutex file_mtx; // Mutex to protect file access

void write_to_file(const std::string& filename, const std::string& data) {
    std::ofstream outfile(filename);
    std::lock_guard<std::mutex> lock(file_mtx);
    outfile << data;
}
```

**4. Thread-Safe Data Structures**

```cpp
class ConcurrentHashMap {
private:
    std::mutex mtx; // Mutex to protect map operations
    std::unordered_map<int, int> map;

public:
    void put(int key, int value) {
        std::lock_guard<std::mutex> lock(mtx);
        map[key] = value;
    }

    int get(int key) {
        std::lock_guard<std::mutex> lock(mtx);
        return map[key];
    }
};
```

**5. Controlling Access to Shared Resources**

```cpp
std::mutex resource_mtx; // Mutex to control access to shared resource

// Thread 1
void thread1() {
    resource_mtx.lock();
    // Access resource
    resource_mtx.unlock();
}

// Thread 2
void thread2() {
    resource_mtx.lock();
    // Access resource
    resource_mtx.unlock();
}
```

**6. Single Instance of a Singleton Class**

```cpp
class Singleton {
private:
    static Singleton* instance; // Singleton instance
    Singleton() {} // Private constructor to prevent direct instantiation

public:
    static Singleton* getInstance() {
        std::call_once(init_flag, [] {
            instance = new Singleton();
        });
        return instance;
    }

    static std::once_flag init_flag; // Initialize the singleton instance only once
};
```

**7. Timed Mutex Acquisition**

```cpp
std::mutex mtx; // Mutex to protect critical section

bool try_lock(int timeout) {
    return mtx.try_lock_for(std::chrono::milliseconds(timeout));
}
```

**8. Deadlock Prevention Using Timeout**

```cpp
std::mutex mtx1, mtx2;

void thread1() {
    mtx1.lock();
    try {
        mtx2.lock();
    } catch (std::system_error& e) {
        // Handle deadlock or timeout
    }
    mtx1.unlock();
}

void thread2() {
    mtx2.lock();
    try {
        mtx1.lock();
    } catch (std::system_error& e) {
        // Handle deadlock or timeout
    }
    mtx2.unlock();
}
```

**9. Deferred Lock Acquisition**

```cpp
std::mutex mtx; // Mutex to protect critical section

void deferred_lock() {
    // Acquire lock only when needed
    std::unique_lock<std::mutex> lock(mtx, std::defer_lock);
    // ... Do some work
    lock.lock();
    // ... Continue protected work
    lock.unlock();
}
```

**10. Transfer Ownership of a Mutex**

```cpp
std::mutex mtx; // Mutex to be transferred

void thread1() {
    std::lock_guard<std::mutex> lock(mtx);
    // ... Protected work
    // Transfer ownership to thread2
    std::unique_lock<std::mutex> lockTransferred(std::move(lock));
}

void thread2() {
    // Acquire ownership of the mutex
    std::unique_lock<std::mutex> lockAcquired(std::move(lockTransferred));
    // ... Continue protected work
}
```

**11. Using a Shared Mutex for Cross-Platform Synchronization**

```cpp
#ifdef _WIN32
    HANDLE mtxHandle = CreateMutex(NULL, FALSE, NULL);
#elif __APPLE__
    pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
#else
    std::mutex mtx;
#endif

// Lock the mutex
#ifdef _WIN32
    WaitForSingleObject(mtxHandle, INFINITE);
#elif __APPLE__
    pthread_mutex_lock(&mtx);
#else
    mtx.lock();
#endif

// Unlock the mutex
#ifdef _WIN32
    ReleaseMutex(mtxHandle);
#elif __APPLE__
    pthread_mutex_unlock(&mtx);
#else
    mtx.unlock();
#endif
```

**12. Explicit Lock-Unlock Coupling**

```cpp
std::unique_lock<std::mutex> lock(mtx); // Acquire lock
// Protected work
lock.unlock(); // Release lock
```

**13. Thread-Safe Lazy Initialization**

```cpp
std::once_flag lazy_flag; // Synchronization flag
std::mutex mtx; // Mutex to protect access to uninitialized object

void initialize() {
    // Initialize the object only if it hasn't been initialized yet
    std::call_once(lazy_flag, [] {
        std::lock_guard<std::mutex> lock(mtx);
        // ... Initialize the object
    });
}
```

**14. Read-Write Lock**

```cpp
std::shared_mutex rwm; // Read-write mutex

void read() {
    std::shared_lock<std::shared_mutex> lock(rwm);
    // Read-only access
}

void write() {
    std::unique_lock<std::shared_mutex> lock(rwm);
    // Write access
}
```

**15. Condition Variable for Thread Synchronization**

```cpp
std::condition_variable cv; // Condition variable
std::mutex mtx; // Mutex to protect access to condition variable

void thread1() {
    std::unique_lock<std::mutex> lock(mtx);
    // Wait for condition to be signaled
    cv.wait(lock);
    // Perform action after condition is signaled
}

void thread2() {
    std::lock_guard<std::mutex> lock(mtx);
    // Signal condition
    cv.notify_all();
}
```

**16. Reader-Writer Problem**

```cpp
std::shared_mutex rwm; // Read-write mutex
int shared_data = 0;

void reader() {
    std::shared_lock<std::shared_mutex> lock(rwm);
    int value = shared_data;
}

void writer() {
    std::unique_lock<std::shared_mutex> lock(rwm);
    shared_data++;
}
```

**17. Locking a Range of Objects**

```cpp
std::lock_guard<std::mutex> lock(mtx); // Lock a single mutex

// Lock a range of objects using a vector of locks
std::vector<std::mutex> locks;
std::vector<std::lock_guard<std::mutex>> heldLocks;

for (auto& mtx : locks) {
    heldLocks.emplace_back(std::lock_guard<std::mutex>(mtx));
}
```

**18. Recursive Mutexes**

```cpp
std::recursive_mutex rmtx; // Recursive mutex

void recursive_function() {
    rmtx.lock();
    // Call itself recursively
    std::lock_guard<std::recursive_mutex> selfLock(rmtx, std::adopt_lock);
    // ...
    rmtx.unlock();
}
```

**19. Mutex Implementation Using Semaphores**

```cpp
#include <semaphore.h>

class Mutex {
private:
    sem_t semaphore;

public:
    Mutex() {
        sem_init(&semaphore, 0, 1);
    }

    void lock() {
        sem_wait(&semaphore);
    }

    void unlock() {
        sem_post(&semaphore);
    }
};
```

**20. Try-Lock with Timeouts**

```cpp
std::mutex mtx; // Mutex to protect critical section

int try_lock(int timeout) {
    return mtx.try_lock_for(std::chrono::milliseconds(timeout));
}

int main() {
    if (mtx.try_lock_for(std::chrono::milliseconds(500))) {
        // Mutex acquired successfully
    } else {
        // Mutex acquisition timed out
    }
}
```

**21. Non-Recursive Mutex**

```cpp
std::mutex mtx; // Mutex to protect critical section

bool try_lock() {
    return mtx.try_lock();
}

int main() {
    if (mtx.try_lock()) {
        // Mutex acquired successfully
    } else {
        // Mutex is already locked, cannot acquire
    }
}
```

**22. Raii-Style Mutex Guard**

```cpp
class MutexGuard {
public:
    MutexGuard(std::mutex& mtx) : mtx(mtx) {
        mtx.lock();
    }

    ~MutexGuard() {
        mtx.unlock();
    }

private:
    std::mutex& mtx;
};

int main() {
    std::mutex mtx;
    {
        MutexGuard lock(mtx);
        // Critical section protected by lock
    }
}
```

**23. Inter-Process Mutex**

```cpp
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

class InterProcessMutex {
private:
    int fd;

public:
    InterProcessMutex(const std::string& name) {
        fd = open(name.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
        flock(fd, LOCK_EX);
    }

    ~InterProcessMutex() {
        flock(fd, LOCK_UN);
        close(fd);
    }
};
```

**24. Immutable Shared Data Structures**

```cpp
std::shared_mutex mtx; // Read-write mutex
int shared_data = 0;

void read() {
    std::shared_lock<std::shared_mutex> lock(mtx);
    int value = shared_data;
}

void write(int new_value) {
    std::lock_guard<std::shared_mutex> lock(mtx);
    shared_data = new_value;
}
```

**25. Thread Pool with Mutex-Protected Queue**

```cpp
std::mutex q_mtx; // Mutex to protect queue operations
std::queue<std::function<void()>> task_queue;

void worker() {
    while (true) {
        std::function<void()> task;
        {
            std::lock_guard<std::mutex> lock(q_mtx);
            if (task_queue.empty()) {
                continue;
            }
            task = task_queue.front();
            task_queue.pop();
        }
        task();
    }
}
```

**26. Locking a Shared Container**

```cpp
std::mutex mtx; // Mutex to protect vector operations
std::vector<int> shared_vec;

void add_to_vec(int value) {
    std::lock_guard<std::mutex> lock(mtx);
    shared_vec.push_back(value);
}

void print_vec() {
    std::lock_guard<std::mutex> lock(mtx);
    for (int i : shared_vec) {
        std::cout << i << " ";
    }
}
```

**27. Protecting Member Variables with Mutexes**

```cpp
class MyClass {
private:
    std::mutex mtx;
    int value;

public:
    void set_value(int new_value) {
        std::lock_guard<std::mutex> lock(mtx);
        value = new_value;
    }

    int get_value() {
        std::lock_guard<std::mutex> lock(mtx);
        return value;
    }
};
```

**28. Semaphore-Based Mutex**

```cpp
#include <semaphore.h>

class Mutex {
private:
    sem_t semaphore;

public:
    Mutex() {
        sem_init(&semaphore, 0, 1);
    }

    void lock() {
        sem_wait(&semaphore);
    }

    void unlock() {
        sem_post

```
