美文网首页
互斥锁的简单实现

互斥锁的简单实现

作者: GayLeague | 来源:发表于2018-08-22 22:48 被阅读0次
    class Peterson: public Lock
    {
       private:
         bool flag[2];
         int turn;
       public:
         void lock() {
            int i = Thread.getId();// 0 or 1
            flag[i] = true;
            turn = j;
            while(flag[j] && turn == j);
          }
          void unlock() {
             int i = Thread.getId();
             flag[i] = false;
          }
    }
    
    class Bakery: public Lock {
      private: 
        bool flag[];
        Label label[];
      public:
        Bakery (int n) {
          flag = new bool[n];
          label = new Label[n];
          for(int i=0; i<n; i++) {
            flag[i] = flase;
            label[i]  =  0;
          }
          void Lock() {
             int i = Thread.getId();
             flag[i] = true;               
             label[i] = max(label[0], ..., label[n-1]) +1;
             while((exist k!=i)(flag[k] && label[k]<label[i])
           }
           void unlock() {
              flag[Thread.getId()] = false;
           }
         }
    }
    
    

    非原创,当时记录到本地,突然想起来就发出来了,侵删。

    相关文章

      网友评论

          本文标题:互斥锁的简单实现

          本文链接:https://www.haomeiwen.com/subject/jzsuiftx.html