gpt4 book ai didi

multithreading - thread::join() 在不应该阻塞时阻塞

转载 作者:行者123 更新时间:2023-12-01 07:25:45 25 4
gpt4 key购买 nike

为了理解如何在 C++11 中使用原子,我尝试了以下代码片段:

#include <iostream>
#include <thread>
#include <atomic>

using namespace std;

struct solution {
atomic<bool> alive_;
thread thread_;

solution() : thread_([this] {
alive_ = true;
while (alive_);
}) { }
~solution() {
alive_ = false;
thread_.join();
}
};

int main() {
constexpr int N = 1; // or 2
for (int i = 0; i < N; ++i) {
solution s;
}
cout << "done" << endl;
}

如果 N 等于 1,则输出为 done 。但是,如果我将其设置为 2,主线程将在 thread::join() 处阻塞。为什么你认为当 N > 1 时我们看不到 done

注意:如果我使用以下构造函数:
    solution() : alive_(true), thread_([this] {
while (alive_);
}) { }

它为 N 的任何值打印 done

最佳答案

如果您不初始化 alive_ 并且仅在线程启动后才设置它,则以下交错执行是可能的:

MAIN: s::solution()
MAIN: s.thread_(/*your args*/)
MAIN: schedule(s.thread_) to run
thread: waiting to start
MAIN: s::~solution()
MAIN: s.alive_ = false
thread: alive_ = true
MAIN: s.thread_.join()
thread: while(alive_) {}

关于multithreading - thread::join() 在不应该阻塞时阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28880089/

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