C++ Join multiple threads

前端 未结 1 1496
醉话见心
醉话见心 2021-01-01 07:35

I would like to do a for-loop which creates more threads.

I\'ve tried with:

int i;
for (i = 0; i < 10; i++) {
    thread t1(nThre);
    t1.join();         


        
相关标签:
1条回答
  • 2021-01-01 08:02

    Your problem is that you start a thread, and join it before starting the next one. You should do like this :

    int i;
    vector<thread> threads;
    
    for (i = 0; i < 10; i++) {
        threads.push_back(thread(nThre));
        cout << "Started thread n'" << i << "\n";
    }
    
    for (i = 0; i < 10; i++) {
        threads[i].join();
        cout << "Joined thread n'" << i << "\n";
    }
    

    First, you start all your threads, then you wait until they are finished.

    For the difference between i++ and ++i, since i is a integer, it makes no difference here. See this answer for more details.

    0 讨论(0)
提交回复
热议问题