0

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()

InfernumDeus
  • 1,185
  • 1
  • 11
  • 33

2 Answers2

1

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
        }
    }
}
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
  • Note that if you require more than one lock, things become way more hairy, and you're going to have to deal with things like lock order and escalating locks (possibly). – Lasse V. Karlsen Feb 14 '15 at 16:47
  • Oh jeesh. Anyway i need only one lock, so thank you! – InfernumDeus Feb 14 '15 at 16:48
  • BTW This is likely to cause `start` to be run multiple times, followed by `end` multiple times. – Aron Feb 14 '15 at 16:58
  • @Aron Using `lock(...) {...}` won't do that, but not checking if already started will. – Lasse V. Karlsen Feb 14 '15 at 16:59
  • I mean if two threads are started to run `start` followed by `end`, then its likely the first thread would acquire the lock...run `start`...wait...the second thread would block on `start`. The first thread finishes `start` and unblocks `start` on the second thread. – Aron Feb 14 '15 at 17:01
0

Use Semaphore or synchronized method (Monitor)

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