InfernumDeus
InfernumDeus

Reputation: 1202

How to lock 2 different methods of the same class in the same time?

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

Answers (2)

user4386714
user4386714

Reputation:

Use Semaphore or synchronized method (Monitor)

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

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

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

Related Questions