如何在同一时间锁定同一类的两个不同方法



我有类:

public class petri {
    public int[] nodes = new int[3];
    public void petri (int n) {
        this.nodes[1] = n;
        this.nodes[2] = 0;
        this.nodes[3] = 0;
    }
    public bool start() {
        if (this.nodes[1] != 0) {
            this.nodes[1]--;
            this.nodes[2]++;
            return true;   
        } else
            return false;
    }
    public bool end() {
        if (this.nodes[2] != 0) {
            this.nodes[2]--;
            this.nodes[3]++;
            return true;   
        } else
            return false;
    }
}

我从并行线程中使用这个类,并且需要这样做:start()end()函数在一次内只能由一个线程使用。我的意思是,如果thread1调用start(),thread2会一直到tread1结束执行start()为止,在此之前thread2不能调用start(()和end()

在要锁定的对象中添加一个对象字段,并在每个要锁定的方法中锁定此对象:

public class petri {
    private readonly object _lock = new object();
    public bool start() {
        lock(_lock)
        {
            // rest of method here
        }
    }
    public bool end() {
        lock(_lock)
        {
            // rest of method here
        }
    }
}

使用信号量或同步方法(监视器)

http://www.albahari.com/threading/part2.aspx

最新更新