简体   繁体   English

具有递归函数的C ++线程

[英]C++ thread with a recursive function

void merge_sort_thread(vector<int>& array) {
if (1 < array.size()) {
    vector<int> array1(array.begin(), array.begin() + array.size() / 2);
    thread first= thread(merge_sort_thread,array1);

    vector<int> array2(array.begin() + array.size() / 2, array.end());
    thread second = thread(merge_sort_thread,array2);
    first.join(); //wait for both ended
    second.join();
    merge (array1.begin(),array1.end(),array2.begin(),array2.end(),array.begin());
}

I am using Xcode to build and run, and it is a build failure. 我正在使用Xcode构建和运行,这是构建失败。 With prompt: 有提示:

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:332:5: Attempt to use a deleted function /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:332:5:尝试使用已删除的功能

I know threading here is not efficient, but I want to know why this not work. 我知道这里的线程效率不高,但是我想知道为什么这行不通。

std::thread deduces the type of bound arguments and stores a copy of them in the thread object. std::thread推导绑定参数的类型,并将其副本存储在线程对象中。 In your case the the argument is deduced to be a reference. 在您的情况下,该参数被推论为参考。 However references, as you know, cannot be copied. 但是,正如您所知,引用不能被复制。 If you want to pass a reference to a function inside std::thread , then you can use std::ref which creates a reference wrapper that is copyable: 如果要传递对std::thread内部函数的引用,则可以使用std::ref创建可复制的引用包装器:

thread first(merge_sort_thread,std::ref(array1));

You're doing copy initialization (see here ), and threads are not allowed to be copyable objects for obvious reasons. 你做的copy initialization (见这里 ),和线程不准是显而易见的原因可复制的对象。

Instead, replace this kind of code 相反,请替换此类代码

 thread foo = thread(...);

With this 有了这个

thread foo(...);

Or, if you don't have phobias (like me...) to ugly code, and you believe in the promises of the 11th C++... 或者,如果您没有恐惧症(例如我...)来编写丑陋的代码,并且您相信第11个C ++的承诺...

thread foo{...};

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

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