线程问题-争用条件

资源争用示例

public class MyThreadObject {
    private int state = 5;

    public void ChangeState() {
        state++;
        if (state == 5) {
            Console.WriteLine ("state = 5");

        }
        state = 5;
    }
}

class MainClass
{
    static void ChangeState(object myObj) {
        MyThreadObject m = myObj as MyThreadObject;
        while (true) {
            m.ChangeState ();
        }
    }

    public static void Main (string[] args)
    {
        MyThreadObject m = new MyThreadObject ();
        Thread t = new Thread (ChangeState);
        t.Start (m);

        new Thread (ChangeState).Start (m);

        Console.ReadKey ();
    }
}

运行结果会不断的输出"state = 5",因为开启了2个线程都在争用同一个类对象中的方法

解决办法,加锁

使用lock(锁)解决争用条件的问题

static void ChangeState(object myObj) {
    MyThreadObject m = myObj as MyThreadObject;
    while (true) {
        lock (m) {
            m.ChangeState ();
        }
    }
}

死锁

public class SampleThread{
    private StateObject s1;
    private StateObject s2;
    public SampleThread(StateObject s1,StateObject s2){
        this.s1= s1;
        this.s2 = s2;
    }
    public void Deadlock1(){
        int i =0;
        while(true){
            lock(s1){
                 lock(s2){
                    s1.ChangeState(i);
                    s2.ChangeState(i);
                    i++;
                    Console.WriteLine("Running i : "+i);
                }
            }
        }
    }
    public void Deadlock2(){
        int i =0;
        while(true){
            lock(s2){
                 lock(s1){
                    s1.ChangeState(i);
                    s2.ChangeState(i);
                    i++;                                    Console.WriteLine("Running i : "+i);
                }
            }
        }
    }
}
var state1 = new StateObject();
var state2 = new StateObject();
new Task(new SampleTask(s1,s2).DeadLock1).Start();
new Task(new SampleTask(s1,s2).DeadLock2).Start();

如何解决死锁

在编程的开始设计阶段,设计锁定顺序

results matching ""

    No results matching ""