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. With prompt:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/thread:332:5: Attempt to use a deleted function
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. 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:
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.
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++...
thread foo{...};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.