我有类:
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