`threads[i] = thread(exec_produce, i + 1)`这行代码为什么不会报错?

发布于 2022-09-06 22:12:26 字数 1363 浏览 15 评论 0

void exec_produce(int duration) {
    //阻止线程运行到duration秒
    this_thread::sleep_for(chrono::seconds(duration));
    //this_thread::get_id()获取当前线程id
    cout << "exec_produce thread " << this_thread::get_id()
        << " has sleeped " << duration << " seconds" << endl;
}

int main(int argc, const char *argv[])
{
    thread threads[5];
    cout << "create 5 threads ..." << endl;
    for (int i = 0; i < 5; i++) {
        threads[i] = thread(exec_produce, i + 1);
    }
    cout << "finished creating 5 threads, and waiting for joining" << endl;
    //下面代码会报错,原因就是copy操作不可用,相当于是delete操作,所以报错
    /*for(auto it : threads) {
        it.join();
    }*/
    for (auto& it: threads) {
        it.join();
    }
    cout << "Finished!!!" << endl;
    system("pause");
    return 0;
}

我想知道为什么threads[i] = thread(exec_produce, i + 1);这行代码不会报错,但是这里

    for(auto it : threads) {
        it.join();
    }

就报错了?这两个地方不都是调用了赋值运算符吗?

我知道有下面这两个规则:

1)move 赋值操作:thread& operator= (thread&& rhs) noexcept,如果当前对象不可 joinable,需要传递一个右值引用(rhs)给 move 赋值操作;如果当前对象可被 joinable,则 terminate() 报错。

2)拷贝赋值操作被禁用:thread& operator= (const thread&) = delete,thread 对象不可被拷贝。

对于move可能还有些疑惑,谢谢大家~~

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文