0

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++?

6
  • 4
    stackoverflow.com/questions/54551371/… stackoverflow.com/questions/41914279/… Commented May 17, 2022 at 7:37
  • Do not join() immediately. It will wait for thread finished. Commented May 17, 2022 at 7:38
  • 2
    You should save thread in a vector or somewhere. Please refer to the questions that Mat provided. Commented May 17, 2022 at 7:40
  • You need to maintain thread objects in a container. You are creating threads in for loop. As soon as next iteration starts, your previous thread object gets destroyed. This could be the probable cause for the exception. Commented May 17, 2022 at 7:43
  • 1
    The thread destructor will call terminate() if it hasn't been joined. So you have to store the thread objects outside the loop. Commented May 17, 2022 at 7:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.