C ++ 11中的线程禁用了复制分配

时间:2018-03-31 13:22:22

标签: c++ c++11

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);是正确的?是不是使用复制功能?我看到规则如下:

1)移动分配操作:线程&amp; operator =(thread&amp;&amp; rhs)noexcept,如果当前对象不可连接,则需要将正确的值引用(rhs)传递给移动赋值操作;如果当前对象可以连接,则terminate()错误。

2)禁用复制分配:thread&amp; operator =(const thread&amp;)= delete,无法复制线程对象。

2 个答案:

答案 0 :(得分:3)

不,这是移动功能。

使用=时,如果可能,执行移动(即,如果传递右值,并且存在移动赋值运算符)。只有在不可能的情况下才会尝试复制。理所当然的是,最便宜的操作是默认操作。

您可以在引用的规则中清楚地看到,=运算符可以表示这两个操作。

答案 1 :(得分:1)

不,代码是正确的。

threads[i] = thread(exec_produce, i + 1);将调用移动分配。 thread(exec_produce, i + 1)是一个r值,因为它在内存中没有已定义的位置(它刚刚创建并且还没有存储在变量中)。因此,将调用移动分配。