简体   繁体   中英

Multithreading with vectors in C++

Based on this code , I am trying to do a simple multithread program where the number of threads is determined in the input arguments as num_threads and these threads must call the same method with a given input parameters.

The problem arises when num_items > num_threads due to the redefinition of thread_id (despite the fact that all the threads are joined after their use).Does anyone know where am I failing?

vector<thread> thread_id;

int it = num_items/num_threads +  (num_items%num_threads != 0);
for(int i = 0; i < it; i++){
    for(int j = 0; j < num_threads; ++j)
        thread_id.push_back(thread(method1, "parameter", i*num_threads + j));

    for(auto& t : threadId)
        t.join();
}

The error code is the following:

terminate called after throwing an instance of 'std::system_error'
  what():  Invalid argument

Since you're only always adding to the vector, the old thread handles stay there and you try to re- join them (along with the new ones) which is a std::system_error as documented .

Try this at the end of your j -loop:

thread_id.clear()

Also, note that a multiple of num_threads will always be created, which will be equal to or greater than num_items . You may want to treat the last iteration differently (just add a condition on the value of i*num_threads + j ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM