简体   繁体   English

C ++中的向量多线程

[英]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. 基于此代码 ,我试图做一个简单的多线程程序,其中在输入参数中将线程数确定为num_threads并且这些线程必须使用给定的输入参数调用相同的方法。

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? 当由于重新定义thread_id而导致num_items > num_threads时出现问题(尽管所有线程在使用后都已连接),有人知道我在哪里失败吗?

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 . 因为你永远只增加了向量,旧的线程句柄呆在那里,并尝试重新join他们(用新的沿),这是一个std::system_error 作为记录

Try this at the end of your j -loop: 在您的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 . 另外,请注意,将始终创建多个num_threads ,等于或大于num_items You may want to treat the last iteration differently (just add a condition on the value of i*num_threads + j ). 您可能希望以不同的方式对待最后一次迭代(只需在i*num_threads + j的值上添加一个条件)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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