代码之家  ›  专栏  ›  技术社区  ›  Taylor

我可以在不读取值的情况下确定数据竞争的结果吗?

  •  3
  • Taylor  · 技术社区  · 6 年前

    我正在努力更好地理解无锁编程:

    假设我们在数据竞赛中有两个线程:

    // Thread 1
    x = 1
    
    // Thread 2
    x = 2
    

    有没有第三个线程可以不读X就知道比赛结果的无锁方法?

    假设线程3使用一个无锁队列,代码是:

    // Thread 1
    x = 1
    queue.push(1)
    
    // Thread 2
    x = 2
    queue.push(2)
    

    然后,可以按以下顺序进行操作:

    x = 1
    x = 2
    queue.push(1)
    queue.push(2)
    

    x = 1
    x = 2
    queue.push(2)
    queue.push(1)
    

    因此,单独拥有一个无锁队列不足以让线程3在比赛后知道x的值。

    1 回复  |  直到 6 年前
        1
  •  4
  •   Domso    6 年前

    如果你知道 x 在比赛开始之前,下面的代码使用原子的读-修改-写操作应该完成这项工作。

    // Notes:
    // x == 0
    // x and winner are both atomic
    // atomic_swap swaps the content of two variables atomically, 
    // meaning, that no other thread can interfere with this operation
    
    //thread-1:
    t = 1;
    atomic_swap(x, t);
    if (t != 0) {
        //x was non zero, when thread-1 called the swap operation
        //--> thread-2 was faster
        winner = 1;
    }    
    
    //thread-2
    t = 2;
    atomic_swap(x, t);
    if (t != 0) {
        //x was non zero, when thread-2 called the swap operation
        //--> thread-1 was faster
        winner = 2;
    }  
    
    //thread-3
    while (winner == 0) {} 
    print("Winner is " + winner);