互斥锁的简单实现

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

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

你可能感兴趣的:(互斥锁的简单实现)