How to give priority to privileged thread in mutex locking?

后端 未结 8 1338
失恋的感觉
失恋的感觉 2020-12-01 02:48

First of all: I am completely a newbie in mutex/multithread programming, so sorry for any error in advance...

I have a program that runs multiple threads. The threads

8条回答
  •  悲哀的现实
    2020-12-01 03:34

    #include 
    #include 
    #include 
    #include 
    
    class priority_mutex {
      std::condition_variable cv_;
      std::mutex gate_;
      bool locked_;
      std::thread::id pr_tid_; // priority thread
    public:
      priority_mutex() : locked_(false) {}
      ~priority_mutex() { assert(!locked_); }
      priority_mutex(priority_mutex&) = delete;
      priority_mutex operator=(priority_mutex&) = delete;
    
      void lock(bool privileged = false) {
        const std::thread::id tid = std::this_thread::get_id();
        std::unique_lock lk(gate_);
        if (privileged)
          pr_tid_ = tid;
        cv_.wait(lk, [&]{
          return !locked_ && (pr_tid_ == std::thread::id() || pr_tid_ == tid);
        });
        locked_ = true;
      }
    
      void unlock() {
        std::lock_guard lk(gate_);
        if (pr_tid_ == std::this_thread::get_id())
          pr_tid_ = std::thread::id();
        locked_ = false;
        cv_.notify_all();
      }
    };
    

    NOTICE: This priority_mutex provides unfair thread scheduling. If privileged thread acquires the lock frequently, other non-privileged threads may almost not scheduled.

    Usage example:

    #include 
    priority_mutex mtx;
    
    void privileged_thread()
    {
      //...
      {
        mtx.lock(true);  // acquire 'priority lock'
        std::unique_lock lk(mtx, std::adopt_lock);
        // update shared state, etc.
      }
      //...
    }
    
    void normal_thread()
    {
      //...
      {
        std::unique_lock lk(mtx);  // acquire 'normal lock'
        // do something
      }
      //...
    }
    

提交回复
热议问题