加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

多线程 – thread :: join()阻止它不应该

发布时间:2020-12-15 05:12:39 所属栏目:Java 来源:网络整理
导读:要了解如何在C 11中使用atomics,我尝试了以下代码片段: #include iostream#include thread#include atomicusing namespace std;struct solution { atomicbool alive_; thread thread_; solution() : thread_([this] { alive_ = true; while (alive_); }) {
要了解如何在C 11中使用atomics,我尝试了以下代码片段:

#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,则输出完成.但是,如果我将其设置为2,主线程将阻塞在thread :: join().当N>为什么你认为我们看不到. 1?

注意:如果我使用以下构造函数:

solution() : alive_(true),thread_([this] {
        while (alive_);
    }) { }

它打印完成N的任何值.

解决方法

如果您没有初始化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_) {}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读