C++ 问题将信息传递给 pthreads
c++ issue passing information to pthreads
我遇到的问题是showData()中的printf调试语句会给我无意义的数字。 即:thread_id是 -1781505888。如果我在设置thread_id、startIndex 和 stopIndex 的值后立即在 createThreads() 中插入 printf 语句,那么这些值将正确打印。当我将threadData作为参数传递给pthread_create或当我在showData()中从threadArg读取数据时,数据以某种方式被损坏。此外,可以假定 N 和 k 的值是整数,N/k 的余数为 0。感谢所有帮助。
编辑:此外,如果它提供了任何额外的信息 - 当我在相同的输入上运行它时,每次运行它时都会得到不同的输出。 有时是无意义的数字,有时所有值都显示为 0,偶尔会出错。
void createThreads(int k){
struct threadData threadData;
int numThreads = k;
int i = 0;
int err = 0;
pthread_t *threads = static_cast<pthread_t*>(malloc(sizeof(pthread_t) * numThreads));
for(i = 0;i<numThreads;i++){
struct threadData threadData;
threadData.thread_id = i;
threadData.startIndex = ((N/k)*i);
if(i == numThreads -1){
threadData.stopIndex = ((N/k)*(i+1))-1;
}
else{
threadData.stopIndex = ((N/k)*(i+1));
}
err = pthread_create(&threads[i], NULL, showData, (void *)&threadData);
if(err != 0){
printf("error creating threadn");
}
}
}
void *showData(void *threadArg){
struct threadData *threadData;
threadData = (struct threadData *) threadArg;
printf("thread id : %dn", threadData->thread_id);
printf("start: %dn", threadData->startIndex);
printf("stop : %dn", threadData->stopIndex);
}
threadData
是你的 for 循环的本地...它在每次迭代时都会超出范围,因此指向它的指针在 showData()
例程中无效。 您可以改为动态分配它并在showData
结束时delete
它。
您可能还希望将threads
数据返回给createThreads
' 调用方,以便它可以join
线程以等待showData
"工作"完成。
例:
...
for(i = 0; i < numThreads; ++i)
{
struct threadData* threadData = new struct threadData;
threadData->thread_id = i;
threadData->startIndex = ((N/k)*i);
if(i == numThreads -1){
threadData->stopIndex = ((N/k)*(i+1))-1;
}
else{
threadData->stopIndex = ((N/k)*(i+1));
}
err = pthread_create(&threads[i], NULL, showData, (void*)threadData);
if(err != 0){
printf("error creating threadn");
exit(1); // probably not worth trying to continue...
}
return threads;
}
void *showData(void *threadArg){
struct threadData* threadData = (struct threadData*)threadArg;
printf("thread id : %dn", threadData->thread_id);
printf("start: %dn", threadData->startIndex);
printf("stop : %dn", threadData->stopIndex);
delete threadData;
}
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何设置一个范围来提取我想要获得的信息
- 系统参数信息A 与 SPI_GETMOUSE 返回 0
- 为什么 gcovr 会生成空覆盖率统计信息?
- C++ PTHREADS - 无效转换无效*(*)()到无效*(*)(无效*)
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 将信息输入到下面显示的结构向量中的正确语法/格式是什么
- 调试符号中缺少 QObject 类信息(编辑但存在其他 Qt 类)
- 为什么数组大小信息可用于"sizeof"运算符和 delete[] 运算符,但在将数组作为参数传递到
- Pisarze - 来自波兰奥林匹克信息学的数据分析任务
- 将数组信息存储到 c++ 向量中有一个"Access violation reading location"
- C++20 个模块在 clang (Windows):在最简单的示例中键入信息错误
- C++ 如何暂停控制台输出,以便用户可以在继续之前阅读信息
- 如何从WebAssembly模块检测浏览器信息?
- Visual Studio 2017 C++,不能使用 typeid() 获取信息对象,缺少指针?;
- 如何实现具有多个平台__FILE__和__LINE__信息的 C/C++ 可变参数日志记录宏?
- 按字母顺序打印存储在字符数组中的信息
- C++ 问题将信息传递给 pthreads