簡體   English   中英

pthreads:允許的線程數

[英]pthreads : allowed number of threads

我已經在一個使用pthreads的小型C程序上工作了幾天。 我昨天花了或多或少花了所有尋找死鎖的bug,但現在我發現這個問題並不是真正的僵局。 以下代碼具有完全相同的問題。

#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
#define NTHREADS 507

pthread_mutex_t runningThreadsMutex;
pthread_cond_t runningThreadsCond;
int runningThreads = 0;

void* HelloWorld(void* arg) {
  sleep(1);

  pthread_mutex_lock(&runningThreadsMutex);
  runningThreads--;
  printf("End thread %d\n", runningThreads);
  pthread_cond_signal(&runningThreadsCond);
  pthread_mutex_unlock(&runningThreadsMutex);

  return NULL;
}

int main() {
  pthread_t thread;

  pthread_mutex_init(&runningThreadsMutex, NULL);
  pthread_cond_init(&runningThreadsCond, NULL);

  for (int i = 0; i < NTHREADS; ++i) {
    pthread_mutex_lock(&runningThreadsMutex);
    printf("Create thread %d\n", runningThreads++);
    pthread_mutex_unlock(&runningThreadsMutex);
    pthread_create(&thread, NULL, HelloWorld, NULL);
  //  pthread_detach(thread);
  }

  pthread_mutex_lock(&runningThreadsMutex);
  while(runningThreads > 0) {
    pthread_cond_wait(&runningThreadsCond, &runningThreadsMutex);
  }
  pthread_mutex_unlock(&runningThreadsMutex);
  return 0;
}

對於NTHREADS <506,上面的代碼似乎在我的筆記本電腦(64位Linux機器)上運行良好。在這種情況下,它打印出如下內容:

Create thread 0
Create thread 1
.
.
.
Create thread 505
End thread 505
End thread 504
.
.
.
End thread 0

並且應該終止。 但是,如果我使用NTHREADS> = 506,例如NTHREADS = 510我得到

Create thread 0
Create thread 1
.
.
.
Create thread 509
End thread 509
End thread 508
.
.
.
End thread 4

它停止而沒有終止。 所以似乎最后四個(510-506 = 4)線程永遠不會終止(或者根本不會啟動?)。

我在舊的32位linux機器上也嘗試了這個代碼。 在那里我得到了相同的行為,除了它適用於NTHREADS <38​​2但不適用於NTHREADS> = 382(而不是506)。

當我搜索一個解決方案時,我也發現了這個問題: http//bytes.com/topic/c/answers/728087-pthreads-limit ,在使用pthread_join時有人遇到同樣的問題(這在工作時可能更自然與pthreads)但他們沒有給出任何好的解釋。

任何人都可以向我解釋我做錯了什么,這個代碼的根本問題是什么? 我想這必須對允許的線程數量有某種限制,但我應該如何處理呢?

您需要檢查pthread_create的返回值。 如果它不為零,則函數無法創建線程。 一個典型的問題是新線程的堆棧內存不足。 例如,每個線程使用1Mb堆棧,系統將需要至少510Mb的可用內存來啟動510個線程。

你為什么要運行這么多線程? 除非你有一個包含數百個處理器的大規模並行系統,否則這些線程將爭奪CPU時間和其他資源。 您可能會以更少的線程(與系統中處理器數量相同的數量級)以最合適的順序完成工作。

添加到Anthony的答案,您可以使用以下代碼重置線程的堆棧分配:

pthread_attr_t threadAttr;
size_t threadStackSize = 65536;   // this is the stack size in bytes, 
                                  // must be over 16384 for Linux 
pthread_attr_init(threadAttr);
pthread_attr_setstacksize(&threadAttr,threadStackSize);

    if( pthread_create(&threadId,&threadAttr,funcn,NULL) != 0 )
    {
        printf("Couldn't create thread\n");
        exit(1);
    }

暫無
暫無

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

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