【发布时间】:2026-02-09 03:20:06
【问题描述】:
我正在尝试逐像素加密 BMP 图像,并使用 pthread 并行加密它们。
我的代码是这样的:
struct arg_struct {
int arg1;
int arg2;
...
};
void* print_message(void* arguments) {
struct arg_struct* args = (struct arg_struct*)arguments;
//Encryption...
// exit from current thread
pthread_exit(NULL);
}
void multiThreadExample() {
cout << "Start..." << endl;
const int NUMBER_OF_THREADS = 50000; // number of pixels
pthread_t thread[NUMBER_OF_THREADS];
arg_struct arg[NUMBER_OF_THREADS];
for (int i=0;i<NUMBER_OF_THREADS;i++) {
arg[i].arg1 = i;
arg[i].arg2 = ... // give values to arguments in arg_struct
pthread_create(&thread[i], NULL, print_message, static_cast<void*>(&arg[i]));
}
for(int i = 0; i < NUMBER_OF_THREADS; i++) {
pthread_join(thread[i], NULL);
}
cout << "Complete..." << endl;
//streaming results to file using filebuf
}
int main() {
multiThreadExample();
return 0;
}
如果图像小到 3*3 就可以了。
如果图像变大,例如 240*164,程序会在 AFTER 打印出“Complete...”时冻结
几分钟后,它显示Segmentation fault (core dumped)。
我不确定是什么让程序在最重的部分(加密)已经完成后冻结。是不是因为这么多线程已经占满了我所有的内存空间?运行时最大占用10G以上。
实际上我已经尝试过不使用多线程,但程序仍然冻结。
【问题讨论】:
-
您需要检查
pthread_create是否成功。 50000 pthreads 是一吨,你不能加入没有成功创建的线程。 -
我觉得
join函数应该成功了吧?因为如果不成功,cout << "Complete..." << endl;就不应该被执行。 -
@TaihouKai -- 不要猜测,而是检查那些会在失败时报告错误的函数的返回码。
-
为什么在 C++ 中使用原始 pthread?我们有
std::thread和朋友。 -
谷歌搜索两个词然后随机选择两个结果之一是...... 不是如何在计算机编程中做出架构决策。 研究你的选择。
标签: c++ multithreading pthreads