Vector of threads

I am trying to write a multi threaded program. However, I end up getting a compilation error saying.

/usr/include/c++/4.8/bits/stl_vector.h:906:34: required from ‘void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::thread; _Alloc = std::allocator<std::thread>; std::vector<_Tp, _Alloc>::value_type = std::thread]’
main.cpp:46:27: required from here
/usr/include/c++/4.8/ext/new_allocator.h:120:4: error: use of deleted function ‘std::thread::thread(const std::thread&)’
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
^
In file included from main.cpp:26:0:
/usr/include/c++/4.8/thread:126:5: error: declared here
thread(const thread&) = delete;
^

Code:

#include <vector>
#include <memory>
#include <thread>
#include <iostream>
#include <string>

class Test
{
private:
public:
void testme(const std::string& _str)
{
std::cout << "Hello "+_str << std::endl;
}
};

int main(const int argc, const char **argv)
{
std::string str = "there";
Test t1/*, t2*/;
std::vector<std::thread> vec_thr;
std::thread thr1(&Test::testme, std::move(t1), std::cref(str));
vec_thr.push_back(thr1);
return 0;
}
Threads cannot be copied, but they can be moved:

1
2
3
    vec_thr.push_back(std::move(thr1));

    for (auto& t : vec_thr) t.join();    // < - necessary. 

If you put your code between code tags it will help people to help you: http://www.cplusplus.com/forum/articles/42672/

I would be tempted to create the threads in place using std::vector::emplace_back like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <thread>
#include <string>
#include <vector>
#include <iostream>

class Test
{
private:
public:
    void testme(const std::string& _str)
    {
        std::cout << "Hello " + _str << std::endl;
    }
};

int main()
{
    std::string str = "there";
    Test t1/*, t2*/;
    std::vector<std::thread> vec_thr;

    // pass the constructor parameters you would have passed to std::thread
    // to the emplace_back() function - they are forwarded to the thread that
    // is constructed "in place" inside the vector
    vec_thr.emplace_back(&Test::testme, std::move(t1), std::cref(str));

    // Don't forget to join all your threads to make sure
    // they complete before moving on/exiting
    for(auto& t: vec_thr)
        t.join();
}
Last edited on
Topic archived. No new replies allowed.