0
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.

John Bupit
  • 10,406
  • 8
  • 39
  • 75
L.Y
  • 3
  • 1
  • 5

2 Answers2

2

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));
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • @L.Y there's no comment so the downvoter probably didn't have a good reason for it. It was possibly done at random or by accident. Feel free to upvote if the answer is helpful. – eerorika Sep 14 '15 at 10:47
0

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{...};
Community
  • 1
  • 1
3442
  • 8,248
  • 2
  • 19
  • 41
  • He's copy initializing with an rvalue and threads *are* movable. It's not a good way to initialize the thread but it should compile, shouldn't it? – eerorika Sep 14 '15 at 08:48
  • Actually I tried both, and result is the same @KemyLand Any other suggestion? – L.Y Sep 14 '15 at 10:40
  • @L.Y: Well, this is no longer standard-obeying behaviour. Are you sure your XCode installation is correct? Are you compiling in C++11 mode? – 3442 Sep 14 '15 at 16:35