Simultaneous Threads in C++ using <thread>

MarioAda picture MarioAda · Jun 14, 2014 · Viewed 9.4k times · Source

I have been looking around and I am not sure why is this happening. I've seen lots of Tuts related to using threads on Linux but not much on what I am sharing right now.

Code:

int j = 0;
while(j <= 10)
{
    myThreads[j] = std::thread(task, j);
    myThreads[j].join();
    j+=1;
}

So I am simply trying to create 10 threads and execute them all. The task is pretty simple and it's been dealt with pretty well but the problem is that not the whole threads are being executed.

It's executing only 1 thread and it's waiting for it to finish then executing the other one etc...

PS: I know that the main function will quit after activating those threads but I read about this and I am sure I can fix it in many ways.

So I want to execute all those threads simultaneously.

Thanks a lot in advance, MarioAda.

Answer

Dervin Thunk picture Dervin Thunk · Jun 14, 2014

You are starting threads and then joining them right away. You need to create, do your work and only then join in some other loop. Besides, you generally put the threads in a vector so you can reference/join them (which you seem to be doing, although in an array, since this is tagged C++, I encourage you to use a std::vector instead).

The strategy is the same as with pthreads before it: your declare an array of threads, push them to run, and then join.

The code below is from here.

#include <thread>
#include <iostream>
#include <vector>

void hello(){
    std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}

int main(){
    std::vector<std::thread> threads;

    for(int i = 0; i < 5; ++i){
        threads.push_back(std::thread(hello));
    }

    for(auto& thread : threads){
        thread.join();
    }

    return 0;
}