所以我正在尝试构建一个服务器,它接受套接字上的连接,然后围绕执行一个函数创建一个线程,该函数使用接受的连接的新打开的文件描述符。我遇到的问题是,当我启动线程时,服务器返回接受另一个连接(如果有的话)但它不会阻塞?它似乎正在从循环中返回,我不知道为什么要这样做。正在运行的代码是:
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]
但是如果 accept 在等待套接字上的新连接时阻塞,那么程序怎么会在打印“After accept”之前终止呢?
最佳答案
问题是你在没有加入它的情况下立即销毁了你的线程:
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>>
完成同样的事情。
关于c++ - 程序在 accept() 之后终止启动线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27049209/