矢量作为pthread_create的输入
vector as input to pthread_create
我将一个结构传递给pthread_create。该结构的一个组成部分是矢量数据。"数据"在每个线程中push_back循环中。当循环的大小较小时,代码将正常运行。当循环很大时。我收到以下错误消息:
munmap_chunk(): 指针无效 munmap_chunk(): 无效指针 已中止(核心已转储)
我试过 m<100,它有效。尝试 m<1000 时,它会显示错误。
// compile using: g++ parallel_2.C -o oo -lpthread
#include <iostream>
#include <cstdlib>
#include <vector>
#include <thread>
using namespace std;
const unsigned NUM_THREADS = std::thread::hardware_concurrency();
//
struct INPUT
{
int start;
int end;
vector<int> data;
};
//
void *Loop(void *param)
{
INPUT *in = (INPUT*)param;
int start = in->start;
int end = in->end;
cout<<" start: "<<start<<" end: "<<end<<endl;
//for(int m=0; m<100000000; m++)
for(int i = start;i < end;i++)
for(int m=0; m<1000; m++) {
in->data.push_back(i);
}
//pthread_exit(NULL);
}
//
int main ()
{
pthread_t threads[NUM_THREADS];
INPUT input[NUM_THREADS];
for( int i=0; i < NUM_THREADS; i++ ){
cout << "main() : creating thread, " << i << endl;
input[i].start = i*5;
input[i].end = input[i].start + 5;
int rc = pthread_create(&threads[i], NULL,
Loop, (void *)&input[i]);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
for(int i = 0; i<NUM_THREADS; i++)
cout<<"!! size of "<<i<<": "<<input[0].data.size()<<endl;
pthread_exit(NULL);
}
munmap_chunk(): 指针无效 munmap_chunk(): 无效指针 已中止(核心已转储)
在此示例的特定情况下(main()
假设线程已完成并查阅修改后的结构),您必须在访问它正在修改的结构之前join()
线程。
for(int i = 0; i<NUM_THREADS; i++)
{
pthread_join(threads[i], NULL);
cout<<"!! size of "<<i<<": "<<input[0].data.size()<<endl;
}
这样,您就可以确定它已完成,并且不再修改结构。
这个问题没有在很少的迭代中出现,因为线程可能已经(但没有什么是确定的)在你最后一次循环之前结束了他们的任务,main()
尝试访问它们的结构。
顺便说一句,您应该考虑使用std::thread
.
(https://en.cppreference.com/w/cpp/thread/thread/thread)
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type