semaphore in c++



  • Hi,

    in der stl gibt es keine semaphore. braucht man sie nicht...
    wie kann man sagen, das z.b. nur x writers gleichzeitig an einem problem arbeiten? kann ich mir dafuer eine semaphore bauen, thread pool, packaged tasks?

    das beispiel hier ist nur ein test hier...

    #include <iostream>
    #include <vector>
    #include <mutex>
    #include <condition_variable>
    #include <thread>
    using namespace std;
    
    class Semaphore {
    public:
        int counter_;
        std::mutex m_;
        std::condition_variable cv_;
    
        Semaphore(int init): counter_(init) {}
    
        void aquire() {
            std::unique_lock<std::mutex> l(m_);
    
            // wait if counter_ == 0
            cv_.wait(l, [this]() { return counter_ != 0; });
    
            counter_--;
        }
    
        void release() {
            std::unique_lock<std::mutex> l(m_);
    
            counter_++;
    
            cv_.notify_one();
        }
    };
    
    class Writer {
    public:
        Semaphore s;
    
        Writer(): s(2) {} // 2 writers at a time, not very usefule for std::cout ... but just to test...
    
        void write() {
            for (int i = 0; i < 100; i++) {
                s.aquire();
    
                cout << "hello world " << i << '\n';
    
                s.release();
            }
        }
    };
    
    int main() {
      // your code goes here
    
      Writer w;
      std::vector<std::thread> worker;
    
      for (int i = 0; i < 10; i++) {
        worker.push_back(std::thread(&Writer::write, &w));
      }
    
      for (auto &e: worker) {
        e.join(); 
      }
    
      return 0;
    }
    

Log in to reply