试图理解3线程的Peterson算法

时间:2014-10-26 05:12:50

标签: multithreading algorithm

我正在尝试使Peterson的算法适用于3个线程,而不是通常的2个。我知道监视器或其他策略对于3个或更多线程更好,但是开始作为一个简单的练习将我的脚趾浸入经过几个小时的尝试调试并围绕这个问题,多线程现在已成为一项燃烧的任务。所以这是通常的算法:

C1 = false
C2 = false
turn = 2

Thread1{
    while (true){
        C1 = true
        turn = 2
        while (C2 == true and turn == 2){
            //spin lock
        }
        //critical section
        C1 = false
    }
}

Thread2{
    while (true){
        C2 = true
        turn = 1
        while (C1 == true and turn == 1){
            //spin lock
        }
        //critical section
        C2 = false
    }
}

Thread1.Start()
Thread2.Start()

我使用2个线程没有问题,但是当我尝试添加3时,一些时髦的东西开始发生(大多数工作,然后不知道2个线程的活动将交错)。以下是我对三通Peterson算法的尝试:

C1 = false
C2 = false
C3 = false
turn = 2

Thread1{
    while (true){
        C1 = true
        turn = 2
        while ((C2 == true or C3 == true) and (turn == 2 or turn == 3)){
            //spin lock
        }
        //critical section
        C1 = false
    }
}

Thread2{
    while (true){
        C2 = true
        turn = 3
        while ((C1 == true or C3 == true) and (turn == 1 or turn == 3)){
            //spin lock
        }
        //critical section
        C2 = false
    }
}

Thread3{
    while (true){
        C3 = true
        turn = 1
        while ((C1 == true or C2 == true) and (turn == 1 or turn == 2)){
            //spin lock
        }
        //critical section
        C3 = false
    }
}

Thread1.Start()
Thread2.Start()
Thread3.Start()

它的行为就像是如此接近正确,但正如我开始弄清楚的那样,在多线程中感觉“接近正确”通常意味着你仍然在数英里之外。

我对3线程彼得森算法的假设是正确的,还是我在这里遗漏了什么?我很难缠绕它。任何帮助是极大的赞赏!

0 个答案:

没有答案