[英]Program with pipes and threads exiting before completion
我正在编写一个带有线程和管道的 c++ 程序。 我正在实现一个并行化算法,我的想法是我有一个将数据写入子线程的主线程。 子线程必须读取这些数据,进行处理,并将结果写回主线程。
我已经剥离了通信核心逻辑的最小复制、编译版本,并注释掉了我有更多代码的地方。 该程序运行并退出而无需输入 complete。 通常,最后打印的 i 值在 1 到 9 之间,程序直接终止,什么也没说。 我希望程序运行完成但我没有收到任何错误并且程序正常退出所以我不确定如何调试。
注意:管道和 Pthreads 是从其他地方强制要求的,是硬性要求。 请不要建议使用 std::thread 或仅在同一地址空间内的线程之间进行通信的解决方案。
#include <iostream>
#include "pthread.h"
#include "unistd.h"
#include <vector>
using namespace std;
void* func (void* args)
{
std::vector<int> v = * (std::vector<int>*)(args);
auto FH = fdopen(v[0], "r");
char buffer[1024];
int buffer_len = 1024;
while (fgets(buffer, buffer_len, FH))
{
std::string x{buffer};
}
// process the result and return it to the parent
return NULL;
}
int main()
{
std::vector<std::vector<int> *> pipes{};
std::vector<pthread_t *> threads{};
for (int i=0; i<20; i++)
{
std::cout<<i<<std::endl;
int fd[2];
if (pipe(fd) < 0)
{
std::cout<<"failed"<<std::endl;
exit(0);
}
int fd2[2];
if (pipe(fd2) < 0)
{
std::cout<<"failed"<<std::endl;
exit(0);
}
std::vector<int> *pipe_info = new std::vector<int>{fd[0], fd[1], fd2[0], fd2[1]};
auto F = fdopen(fd[1], "w");
pthread_t *thread = new pthread_t;
threads.push_back(thread);
pipes.push_back(pipe_info);
pthread_create(thread, NULL, func, (void*) pipe_info);
for (int i=0; i<100; i++)
fprintf(F, "%d", 3);
}
// read the data returned from the child threads
// using fd2 (indices 2,3) in each pipe in pies.
// free all allocated memory
for (auto thread: threads)
{
pthread_join(*thread, NULL);
delete thread;
}
std::cout<<"complete"<<std::endl;
return 0;
}
我无法重现该问题,而且您描述的症状似乎不太可能。 在我的系统上,程序打印出所有数字,但没有终止,而是挂起。
原因是pipe()
不是构造函数; fdopen()
也不是构造函数。 是c接口,离开scope是不会关闭的,必须手动关闭fds和FILE。 您不这样做,线程会在fgets
中耐心等待更多数据或EOF
。 在main
关闭 pipe 的写入端之前,不会有EOF
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.