所以我正在尝试构建一个接受套接字上的连接的服务器,然后围绕执行一个使用新打开的连接文件描述符的函数创建一个线程。我遇到的问题是,当我启动线程时,服务器返回接受另一个连接(如果有的话),但它没有阻止?它似乎从循环中返回,我不知道它为什么这样做。正在运行的代码是:
listen(sockfd,10);
int i = 0;
for(;;)
{
std::cout << "Before accept" << endl;
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
std::cout << "After accept" << endl;
if (newsockfd < 0)
{
std::cout << newsockfd << ": Error on accept" << endl;
continue;
}
else
std::cout << newsockfd << ": Connection accepted!" << endl;
boost::thread(boost::bind(&Class::FunctionToRun, this, newsockfd)).start_thread();
std::cout << ++i << endl;
}
脚趾控制台的输出是:
Socket opened! fd = 3
Before accept
After accept
4: Connection accepted!
1
Before accept
[program terminates]
但是如果在套接字上等待新连接时接受阻塞,那么在打印“接受后”之前程序是如何终止的呢?
答案 0 :(得分:1)
问题是你在没有加入它的情况下立即销毁你的线程:
boost::thread(boost::bind(&Class::FunctionToRun, this, newsockfd)).start_thread();
// already dead here
std::cout << ++i << endl;
}
如果你想让你的线程闲逛,你需要将它们存储在某个地方:
std::vector<std::unique_ptr<boost::thread>> threads;
for (;;) {
// ...
threads.emplace_back(new boost::thread(boost::bind(...)));
// thread is still alive here
std::cout << ++i << endl;
}
如果不是C ++ 11,那么你可以使它成为vector<boost::shared_ptr<boost::thread>>
来完成同样的事情。