gpt4 book ai didi

c++ - N3600 中的 `latch` 样本中是否存在竞争条件?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:38:12 26 4
gpt4 key购买 nike

提议包含在 C++14(又名 C++1y)中的是一些新的线程同步原语:锁存器和屏障。提案是

这听起来是个好主意,示例使它看起来对程序员非常友好。不幸的是,我认为示例代码调用了未定义的行为。该提案对 latch::~latch() 说:

Destroys the latch. If the latch is destroyed while other threads are in wait(), or are invoking count_down(), the behaviour is undefined.

注意它说的是“in wait()”而不是“blocked in wait()”,正如count_down()的描述> 使用。

然后提供以下示例:

An example of the second use case is shown below. We need to load data and then process it using a number of threads. Loading the data is I/O bound, whereas starting threads and creating data structures is CPU bound. By running these in parallel, throughput can be increased.

void DoWork()
{
latch start_latch(1);
vector<thread*> workers;
for (int i = 0; i < NTHREADS; ++i) {
workers.push_back(new thread([&] {
// Initialize data structures. This is CPU bound.
...
start_latch.wait();
// perform work
...
}));
}
// Load input data. This is I/O bound.
...
// Threads can now start processing
start_latch.count_down();
}

在线程从 wait() 唤醒和返回,以及闩锁离开范围时销毁之间是否存在竞争条件?除此之外,所有的 thread 对象都被泄露了。如果调度程序在 count_down 返回之前没有运行所有工作线程并且 start_latch 对象离开范围,那么我认为将导致未定义的行为。据推测,解决方法是在 count_down 之后但在返回之前迭代 vector 和 join()delete 所有工作线程。

  1. 示例代码有问题吗?
  2. 您是否同意提案应该展示一个完整正确的示例,即使任务非常简单,以便审阅者了解使用体验会是什么样?

注意:一个或多个工作线程可能尚未开始等待,因此将在已销毁的锁存器上调用 wait()


更新:现在有一个新版本的提案,但是代表性的例子没有改变。

最佳答案

感谢您指出这一点。是的,我认为示例代码(在辩护中旨在简明扼要)已损坏。它可能应该等待线程完成。

任何允许线程在 wait() 中被阻塞的实现几乎肯定会涉及某种条件变量,并且在线程尚未退出 wait() 时销毁闩锁可能是未定义的。

不知道有没有时间更新论文,但我可以确定下一个版本是固定的。

阿拉斯代尔

关于c++ - N3600 中的 `latch` 样本中是否存在竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16241463/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com