简体   繁体   English

在C ++ 11中为线程禁用了副本分配

[英]Copy assignment is disabled for thread in 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;
 }

I want to know why the code threads[i] = thread(exec_produce, i + 1); 我想知道为什么代码threads[i] = thread(exec_produce, i + 1); is correct? 是正确的? Is it not use the copy function? 是否不使用复印功能? I see the rule as follows: 我看到规则如下:

1) move Assignment operation: thread& operator= (thread&& rhs) noexcept, if the current object is not joinable, you need to pass a right value reference (rhs) to the move assignment operation; 1)移动分配操作:thread&operator =(thread && rhs)noexcept,如果当前对象不可连接,则需要向移动分配操作传递一个正确的值引用(rhs); if the current object can be joinable, then terminate () error. 如果当前对象可以连接,则终止()错误。

2) Copy assignment is disabled: thread& operator= (const thread&) = delete, thread object cannot be copied. 2)禁用复制分配:thread&operator =(const thread&)= delete,无法复制线程对象。

No, it's the move function. 不,这是移动功能。

When using = , a move is performed if possible (that is, if passing an rvalue, and if a move assignment operator exists). 使用= ,如果可能(即,传递一个右值并且存在一个移动赋值运算符),将执行移动。 Only if not possible will a copy be attempted instead. 只有在不可能的情况下,才会尝试进行复制。 It should make sense that the cheapest operation is the default. 应该以最便宜的操作为默认设置。

You can clearly see in the quoted rules that both operations may be represented by the = operator. 您可以在引用的规则中清楚地看到,两个操作都可以由=运算符表示。

No, the code is correct. 不,代码正确。

The line threads[i] = thread(exec_produce, i + 1); threads[i] = thread(exec_produce, i + 1); will call the move assignment. 将调用移动分配。 thread(exec_produce, i + 1) is a r-value because it does not have a defined location in memory (it just been created and wasn't stored in a variable yet). thread(exec_produce, i + 1)是一个r值,因为它在内存中没有定义的位置(它刚刚创建并且尚未存储在变量中)。 Therefore, the move assignment will be called. 因此,将调用移动分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM