簡體   English   中英

Linux C ++線程已死,但“掛起”-線程限制

[英]Linux C++ threads are dead, but “hanging” - thread limit

我的一個朋友正在嘗試用C ++修復為Windows在Linux下工作而編寫的自定義http服務器。 我試圖幫助他,但發現的一切似乎太明顯了。

該應用會在每次請求進入時創建一個線程。該線程為請求提供服務並結束。 經過一定數量的請求(超過300個)后,不再創建新線程。

我發現的全部是,可以創建的線程數量有限。 但是看起來成品線程仍然存在。 這是代碼的問題,還是線程處理程序永遠不會被釋放?

這是我的朋友從應用程序中提取的一些代碼:

pthread_t threadID;

StartingArgs *arg = new StartingArgs( &(this->cameraCounts), mapToSend,&(this->mapMutex), &(this->mutex), this->config );

if( pthread_create(&threadID, NULL, (this->startingRoutine) , (void*)arg ) != 0 )
    {
        ConsoleMessages::printDate();
        cout<< "snapshot maker: new thread creation failed\n";
    }

void *CameraCounter::startingRoutine( void *arg )
{
//stuff to do. removed for debugging

    delete realArgs;
    return NULL;
}

看起來您有一堆“可連接”線程。 他們正在等待有人在他們身上調用pthread_join()。 如果您不想這樣做(例如,獲取線程的返回值),則可以將線程創建為“分離的”:

pthread_t threadID;
pthread_attr_t attrib;

pthread_attr_init(&attrib); 
pthread_attr_setdetachstate(pthread_attr_t &attrib, PTHREAD_CREATE_DETACHED);

StartingArgs *arg = new StartingArgs( &(this->cameraCounts), mapToSend,&(this->mapMutex), &(this->mutex), this->config );

if( pthread_create(&threadID, &attrib, (this->startingRoutine) , (void*)arg ) != 0 )
{
        ConsoleMessages::printDate();
        cout<< "snapshot maker: new thread creation failed\n";
}

pthread_attr_destroy(&attrib);

void *CameraCounter::startingRoutine( void *arg )
{
//stuff to do. removed for debugging

    delete realArgs;
    return NULL;
}

完成后必須加入線程( pthread_join ,另請參見wait(2) ),或者將SIGCHILD處理程序設置為SIG_IGN。

我建議您的朋友創建一個線程池,並將工作項發布到線程池中。 如果有可用的線程服務該工作項,則分配一個線程,並為其分配工作項。 如果沒有可用線程,則請求應掛起,直到有新線程可用。 這樣,他可以防止拒絕服務攻擊期間自己消耗過多的系統資源。

如果一次不可能處理不超過30個請求,則線程池最多應包含30個線程。 這樣,在拒絕服務攻擊期間,系統資源分配將是可預測的,而不依賴於任意系統限制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM