【发布时间】:2011-09-30 10:45:22
【问题描述】:
如果我将 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);
}
【问题讨论】:
-
运行命令“ulimit -a”,看看你有没有设置线程数。这表示特定用户可以创建的线程或进程数。
标签: c multithreading pthreads