Home > Backend Development > C++ > Can C 0x Semaphores Be Emulated Using Mutexes and Condition Variables?

Can C 0x Semaphores Be Emulated Using Mutexes and Condition Variables?

DDD
Release: 2024-12-26 08:08:12
Original
121 people have browsed it

Can C  0x Semaphores Be Emulated Using Mutexes and Condition Variables?

Can You Use Semaphores in C 0x?

Semaphore-based synchronization is essential for thread communication. In the absence of semaphores in C 0x, it seems like a deadlock.

Semaphore Emulation with Mutex and Condition Variables

Fortunately, a semaphore can be recreated using a mutex and a condition variable. Here's a straightforward implementation:

#include <mutex>
#include <condition_variable>

class semaphore {
    std::mutex mutex_;
    std::condition_variable condition_;
    unsigned long count_ = 0; // Initialized as locked.

public:
    void release() {
        std::lock_guard<decltype(mutex_)> lock(mutex_);
        ++count_;
        condition_.notify_one();
    }

    void acquire() {
        std::unique_lock<decltype(mutex_)> lock(mutex_);
        while(!count_) // Handle spurious wake-ups.
            condition_.wait(lock);
        --count_;
    }

    bool try_acquire() {
        std::lock_guard<decltype(mutex_)> lock(mutex_);
        if(count_) {
            --count_;
            return true;
        }
        return false;
    }
};
Copy after login

This emulation provides the fundamental behaviors of semaphores:

  • release() signals an event that may be waiting on the semaphore.
  • acquire() waits for a signal before continuing execution.
  • try_acquire() checks for and grabs a permit if available, without blocking.

The above is the detailed content of Can C 0x Semaphores Be Emulated Using Mutexes and Condition Variables?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template