允许给定服务器中线程数的连接

Allowing connections given the number of threads in server

本文关键字:线程 连接 服务器      更新时间:2023-10-16

每个连接都需要一个线程,目前,我们只允许每个周期有一定数量的连接。因此,每次用户连接时,如果我们在上次设置检查时间的某个时间段内,我们都会增加计数器。

1.get current_time = time(0)
2.if current_time is OUTSIDE certain period from check_time,
  set counter = 0, and check_time = current_time.
3.(otherwise, just leave it the way it is)
4.if counter < LIMIT, counter++ and return TRUE
5.Otherwise return FALSE

但这实际上与我们服务器中运行的线程数量无关,因此我正在考虑一种根据此数字允许连接的方法。

问题是我们实际上使用了第三方API,我们不知道连接会持续多久。首先,我想创建一个子线程并在其上运行ps以将结果传递给父线程,但是似乎需要更多时间,因为我必须解析输出结果才能获得线程总数等。我实际上不确定我是否有意义..顺便说一下,我正在使用c ++。你们对我如何实施新的检查方法有什么建议吗?将不胜感激。

属于进程 [pid] 的每个线程都会有一个/proc/[pid]/task目录(从 Linux 2.6.0-test6 开始(。查看 man proc 以获取文档。假设你知道线程池的pid,你可以只计算这些目录。

你可以使用 boost::filesystem 从 c++ 中做到这一点,如下所述:

如何使用 boost::filesystem 计算目录中的文件数?

我假设你使用的是Linux。

好的,如果您知道连接正在使用的线程的 TID,那么您可以在单独的线程中等待该对象,然后可以递减计数器。

至少我知道你可以用 MSVC 做到这一点......

bool createConnection()
{
    if( ConnectionMonitor::connectionsMaxed() )
    {
        LOG( "Connection Request failed due to over-subscription" );
        return false;
    }
    ConnectionThread& connectionThread = ThreadFactory::createNewConnectionThread();
    connectionThread.startConnection();
    ThreadMonitorThread& monitor = ThreadFactory::createThreadMonitor(connectionThread);
    monitor.monitor();
}

和在线程监视器线程

ThreadMonitorThread( const Thread& thread )
{
    this.thread = thread;
}
void monitor()
{
    WaitForSingleObject( thread.getTid() );
    ConnectionMonitor::decrementThreadCounter();
}

当然,ThreadMonitorThread需要一些特殊权限才能调用递减,而ThreadFactory可能需要相同的权限来递增它。

您还需要担心如何正确编码...谁拥有对象以及异常和错误等怎么办...