首页 文章

程序在accept()之后终止启动线程

提问于
浏览
0

所以我正在尝试构建一个接受套接字上的连接的服务器,然后围绕执行一个使用新接受的连接的文件描述符的函数创建一个线程 . 我遇到的问题是,当我启动线程时,服务器返回接受另一个连接(如果有),但它没有阻止?它似乎从循环中返回,我不知道它为什么这样做 . 正在运行的代码是:

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]

但是如果在等待套接字上的新连接时接受阻塞,那么程序如何在“接受后”打印之前终止?

1 回答

  • 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>> 来完成同样的事情 .

相关问题