Reputation: 1202
I have class:
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;
}
}
I use this class from parallel threads and need to do so: start() and end() functuions must be used only by 1 thread in 1 time. I mean, if thread1
call start(), thread2
weit until tread1
end performing start() and before this thread2
can't call start() and end()
Upvotes: 0
Views: 942
Reputation:
Use Semaphore or synchronized method (Monitor)
http://www.albahari.com/threading/part2.aspx
Upvotes: 0
Reputation: 391336
Add an object field to your object to lock on and lock this object in each method you want to lock out together:
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
}
}
}
Upvotes: 1