How to handle a bunch of threads?

Hello there, I want to start a bunch of threads, but i don't know how I could do this. Here is my try. I would be glad if somewhere could help me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <thread>
#include <vector>

void do_what( const std::string msg, int i)
{
    std::cout << msg << i << std::endl;
}

int main()
{
    std::vector<std::thread> tv;
    for (int i =0; i < 6; ++ i)
    {
        tv.push_back(tv[i](do_what , "Here runs a thread ", i));
    }
    for (int i = 0; i < 6; ++ i)
    {
        tv[i].join();
    }
}
Your problems are in line 15.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <thread>
#include <vector>

void do_what( const std::string msg, int i)
{
    std::cout << msg << i << std::endl;
}

int main()
{
    std::vector<std::thread> tv;
    for (int i =0; i < 6; ++ i)
    {
        tv.emplace_back(do_what , "Here runs a thread ", i);
    }
    for (int i = 0; i < 6; ++ i)
    {
        tv[i].join();
    }
}
Use emplace_back:

tv.emplace_back(do_what , "Here runs a thread ", i);

See:

http://www.cplusplus.com/reference/vector/vector/emplace_back/
Thank you both.
For the sake of completeness - if some other searches for the topic here - I found another solution which is feasable if the count of threads will be known: By holding the threads inside an array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <thread>
#include <array>

void do_what( const std::string msg, int i)
{
    std::cout << msg << i << std::endl;
}

int main()
{
    std::array<std::thread, 6> ta;
    for (std::size_t i = 0; i < ta.size(); ++ i)
    {
        ta[i] = std::thread(do_what, "Here runs thread ", i);
    }
    for (std::size_t i = 0; i < ta.size(); ++ i)
    {
        ta[i].join();
    }
}
Topic archived. No new replies allowed.