'Unable to create real multithreading in C++ (using for loop)

I am new to C++ and I am trying to create multiple threads using for loop. Here is the code

#include <iostream>
#include <thread>
class Threader{
   public:
        int foo(int z){
            std::cout << "Calling this function with value :" << z << std::endl;
            return 0;
        }
};

int main()
{
    Threader *m;
    std::cout << "Hello world!" << std::endl;
    std::thread t1;
    for(int i = 0; i < 5; i++){
        std::thread t1(&Threader::foo, m, i);
        t1.join();

        }
    return 0;
}

This is the output

enter image description here

As you can see the function I am calling is being invoked using Thread 5 times, but I have to do a t1.join inside the for loop. Without the join the for loop fails in the very first iteration. Like shown here enter image description here

But if I use the join(), then the threads are being created and executed sequentially cause join() waits for each thread completion. I could easily achieve Actual multithreading in Java by creating Threads in a loop using runnable methods.

How can I create 5 threads which would run absolutely parallel in C++?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source