You are not logged in.
Pages: 1
In our concurrent tcp server program, once the connection comes, the program create a thread to process acception. When the client exit, the server closed socket and the thread exited, the problem is the memory can not release normally. The code looks like the followings:
main()
{
.......
while(1==1)
{
channel=srv_accept(sockfd,(struct sockaddr *)&tcp_cli_addr,&length);
if(channel<0)
{
//cout<<"channel ="<<channel<<" retry srv_accept ...."<<endl;
continue;
}
num=-1;
// find the nonused pthread number.
for(int i=0;i<MAX_REPORT_NUM;i++)
{
if(pth_struct[i].flag<0)
{
num=i;
break;
}
}
printf("num is %d \n",num);
for(int i=0;i<MAX_REPORT_NUM;i++)
{
printf("....pos=%d flag=%d ......\n",i,pth_struct[i].flag);
}
if(num<0)
{
Tcp_close(channel);
continue;
}
pthch[num].channel=channel;
pthch[num].pos=num;
pth_struct[num].flag=1;
pthread_create(&pth_struct[num].pthread_no,&attr,(pthread_startroutine_t)channel_handler,
(pthread_addr_t *)&pthch[num]);
}
}
int channel_handler(struct pthname_channel *recv_s=NULL)// handling the tcp message.
{
.......
while(1==1)
{
ret=Tcp_read(recv_s->channel,(char *)&ptr,sizeof(struct MESS_BLOCK));
if(ret<=0)
{
printf("@@@@@@@@@@@@ ------ Tcp_read err : ---------- @@@@@@@@@@@@@ \n");
fflush(stdout);
Tcp_close(recv_s->channel);
pth_struct[recv_s->pos].flag=-1;
tid = pthread_self();
pthread_detach((pthread_t *)&tid);
pthread_exit(0);
break;
}
// processing packets .
}
We wants the program can free the thread resource normally once the connection closed and thread exit, any suggestion?
Offline
As long as you don't allocate memory within the thread itself(malloc/calloc/new), there can't be a mem leak. The resources needed by the thread itself might not be freed in modern Linux systems though. Instead the resource block is normally kept in some kind of cache for re-use to speed things up. So, the program should become bigger only until you've had the max number of threads your program uses in parallel and then stay at this level.
Your architecture is highly ineficient though. Instead of the accept in the main thread, you should just do a select, poll or epoll to see if the "sockfd" is readable and then let the work thread do the accept. Start the max number of threads beforehand and let them wait at a semaphore. If the "sockfd" is readable just open the semaphore to start one worker. This way you don't have to create a thread each time, what will speed things up considerably.
Offline
Pages: 1