使用组合树死锁问题的共享计数器

时间:2015-04-26 04:13:12

标签: multithreading algorithm counter

我正在使用组合树概念开发共享计数器增量应用程序。我的目标是使这个应用程序在2个n核心上工作,例如4,8,16,32等。这个算法可能会在任何线程故障时出错。假设是没有线程失败或线程非常慢。

  • 两个线程在叶节点竞争,后一个线程到达树上。
  • 第一个到达的人等到第二个上升到层次结构并返回正确的返回值。
  • 第二个线程唤醒第一个线程
  • 每个帖子都获得正确的fetchAndAdd值

但是这个算法有时被锁定在内部(nodes [index] .isActive == 1)或while(nodes [index] .waiting == 1)循环。我没有看到任何死锁的可能性,因为每个节点只有两个线程竞争。你们能帮我解决一下这个问题吗?

int increment(int threadId, int index, int value) {
    int lastValue = __sync_fetch_and_add(&nodes[index].firstValue, value);
    if (index == 0) return lastValue;
    while (nodes[index].isActive == 1) {
    }
    if (lastValue == 0) {
        while(nodes[index].waiting == 1) {
        }
        nodes[index].waiting = 1;
        nodes[lindex].isActive = 0;
    } else {
        nodes[index].isActive = 1;
        nodes[index].result = increment(threadId, (index - 1)/2, nodes[index].firstValue);
            nodes[index].firstValue = 0;
            nodes[index].waiting = 0;
    }
    return nodes[index].result + lastValue;
}

1 个答案:

答案 0 :(得分:0)

我认为这不会适用于1核心。你无限循环isActive,因为你不能将isActive设置为0,除非它是0。

我不确定你的代码是否有一种机制可以阻止它,但是,这是我最好的解决方案以下是运行并导致问题的线程:

离)

thread1                         thread 2
nodes[10].isActive = 1
                                //next run on index 10
                                while (nodes[index].isActive == 1) {//here is the deadlock}

很难准确理解这里发生了什么/您正在尝试做什么,但我建议您以某种方式需要能够停用节点[index] .isActive。您可能希望在函数结束时将其设置为0