簡體   English   中英

運行多個線程時C pthread分段錯誤

[英]C pthread segmentation fault when running many threads

如果我將nThreads保持在300以下,則以下代碼正在運行,沒有任何問題,但是例如,如果我輸入400,則會出現分段錯誤。 我認為這與最大線程數有關,但是我不確定如何允許更多線程,或者至少如何確定我可以運行的最大線程數。 任何想法? 提前致謝

#include <stdlib.h>
#include <pthread.h>
#include <malloc.h>
#include <unistd.h>

void* thread(void* arg);

int counter=0;
pthread_mutex_t counterMutex = PTHREAD_MUTEX_INITIALIZER;

int main(){
    int nThreads = 0;
    printf("How many threads? ");
    scanf("%d", &nThreads);
    pthread_t* threads = (pthread_t*)malloc(nThreads*sizeof(pthread_t));

    for(int i=0; i < nThreads; i++){
        pthread_create(&threads[i], NULL, thread, (void*)&i);
    }
    for(int i=0; i < nThreads; i++){
       pthread_join(threads[i], NULL);
    }
    printf("counter is %d\n\n", counter);
    exit(0);
}

void* thread(void* arg){
    pthread_mutex_lock(&counterMutex);
    counter++;
    printf("thread %d, counter is %d\n\n", *(int*)arg, counter);
    pthread_mutex_unlock(&counterMutex);
    pthread_exit(NULL);
}

您無需檢查pthread_create成功還是失敗。 如果失敗了,你風調用pthread_join與無效pthread_t

如果要創建那么多線程,除非您在超級計算機上,否則您做錯了。 1990年代的方法是為每個“狀態”(連接,任務等)創建一個線程,但是當前(正確的方法)是僅創建與CPU /核心(給定或占用)數量一樣多的線程,然后使用異步事件拉開其余的時間。

為什么甚至需要400個線程? 您是否意識到擁有大量額外同步的線程會極大地降低程序運行速度?

pthread_mutex_init不會出錯! 並嘗試錯誤條件

暫無
暫無

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

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