【问题标题】:Big-Oh complexity of multithreaded code多线程代码的大复杂度
【发布时间】:2012-08-21 13:50:19
【问题描述】:

如何指定受多线程影响的算法的运行时间?

例如,CompareAndSet 循环可能永远不会被满足(如果你很不走运的话)

AtomicReference<ContainerOfItems> oldContainer;

void AddItem(Item aItem)
{
    ContainerOfItems newContainer;

    do
    {
        newContainer = null;
        newContainer = new ContainerOfItems();
        newContainer.CopyContents(oldContainer);
        newContainer.Add(aItem);
    }
    while (!CompareAndSet(oldContainer, newContainer));

    oldContainer = null;
}

在这个例子中(看起来很像 Java,但实际上是伪代码)CopyContents 操作可能需要很长时间,这样 oldContainer 已被其他线程替换,导致 CompareAndSet 失败。这段代码的运行时间是多少?

【问题讨论】:

    标签: concurrency time-complexity


    【解决方案1】:

    这段代码的运行时间是多少?

    程序的整体运行时间很大程度上取决于copyContents(...) 需要多长时间以及对导致compareAndSet(...) 失败的竞争条件的频率的预测。这取决于同时运行的线程数。

    但是,我怀疑就 Big-O 而言,由于compareAndSet(...) 而循环的次数并不重要。例如,如果一个 copyContents(...) 需要 O(N) 时间来运行,平均它必须循环 3 次才能完成 compareAndSet(...),并且你运行它 N 次以添加所有项目,它是 O( N^2) -- 3 因为常数而退出。

    另外,因为你是在暗示并发,也会有一个因素速度的提高,因为算法将是多线程的,但这也只是一个常数因素的提高,不会影响 Big-O。因此,可以通过查看 copyContents(...) 次(我假设)N 的 Big-O 来计算 Big-O。

    【讨论】:

      猜你喜欢
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-05
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多