Linux下的多线程问题

写了一段测试代码,不停地创建退出线程,发现只能创建303个线程,第304个时就cannot allocate memory。代码如下:
#include  < stdlib.h >
#include 
< errno.h >
#include 
< pthread.h >
#include 
< string .h >
#include 
< fcntl.h >
#include 
< netinet / in .h >
#include 
< arpa / inet.h >
#include 
< sys / wait.h >
#include 
< sys / socket.h >
#include 
< sys / types.h >
#include 
< sys / times.h >
#include 
< unistd.h >

#define  SLEEPTIME 10000
#define  SOCKET_ERROR -1

void *  ExchangeData( void   * lpVar);

int  g_nThread  =   0 ;

#define  THREAD_STACK_SIZE PTHREAD_STACK_MIN

int  main( int  argc,  char *  argv[])
{
pthread_t pID;
int  ret;
printf(
" %d\n " , PTHREAD_STACK_MIN);
getchar();
while ( 1 ){
        
// int *lpVar = (int *) malloc(sizeof(int));
        
// *lpVar = g_nThread;
        pthread_attr_t  attr;
        ret 
=  pthread_attr_init( & attr);
        
if  (ret  !=   0 ) {
                printf(
" Failed to pthread_attr_init\n " );
        }
       
//  ret = pthread_attr_setstacksize(&attr, THREAD_STACK_SIZE);
         if  (ret  !=   0 ) {
                printf(
" Failed to setstacksize:%d %s\n " , errno, strerror(errno));
        }
        usleep(
1000 );
        
int   * lpVar  =  ( int   * )malloc( sizeof ( int ));
        
* lpVar  =   9 ;
        
if (pthread_create( & pID,  & attr, ExchangeData,( void   * )lpVar)  !=   0 ) {
                printf(
" err : %d : %s\n " , errno, strerror(errno));
                usleep(
1000 * 1000 );
                
// continue;
                 break ;
        }
        printf(
" thread num : %d\n " , g_nThread);
        g_nThread
++ ;
}
return   0 ;
}

//
void *  ExchangeData( void   * lpVar)
{
        
char  szBuff[ 1024 ];
        
int   *  pInt  =  lpVar;
        free(pInt);
        szBuff[
0 =   ' i ' ;
        usleep(
1000 * 1000 );
        
int  i = 0 ;
        
while (i  < 1024 ) {
                szBuff[i] 
=  i % 128 ;
                i
++ ;
        }
        printf(
" thread %d destroyed!\n " , g_nThread);
        pthread_exit(
0 );
        
return   0 ;
}
默认情况下(即不设置线程的堆栈大小),该进程只能创建303个线程,当改变子线程的堆栈大小后,可以增加线程数,但还是有一个上限。当创建的线程总数达到这个上限后,就不能再创建新的线程了,这时不得不重启程序,所以要创建服务器程序,需要寻找新的多线程的处理方法。
补充一点:在创建线程之前建议usleep一下。
注意:这里的线程数不是指同一时间端存活的线程数,而是程序总共创建的线程数。

转载于:https://www.cnblogs.com/justforfan528/articles/908267.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值