evan

For the lasting love

导航

循环pthread_create导致虚拟内存上涨(续2)

经过ellitto的检查,发现前面的问题是由于主线程里判断是否创建线程,如果是的话就创建线程,但是当创建子线程完之后,父线程仍然在运行,因此又进行判断,此时条件语句结果仍然没有改变,因此下面使用信号量semaphore进行同步,当父线程创建子线程之后,使用sem_wait()进行等待直到子线程修改了条件语句的结果之后调用sem_post(),才允许父线程继续运行

修改后的代码如下

代码
///
//include all header files needed
///

sem_t sem_ss;
sem_t sem_up;

void * Client_TS_handle_ss_local_data_cmd(void * arg)
{
printf(
"enter local ss handler\n");

///
//forword the real-time data received from client-com-server to web-server
//through socket communication
///

///
//modify the result of the call of select in main()
///
sem_post(&sem_ss);

printf(
"leave local ss handler\n");
pthread_detach(pthread_self());
pthread_exit(NULL);
}

void * Client_TS_handle_up_local_data_cmd(void * arg)
{
printf(
"enter local up handler\n");

///
//forword the historical data received from client-com-server to web-server
//through socket communication
///

///
//modify the result of the call of select in main()
///
sem_post(&sem_ss);

printf(
"leave local up handler\n");
pthread_detach(pthread_self());
pthread_exit(NULL);
}

int main()
{
///
//initialize the server sockets
//Local_UP_Socket_fd
//Local_SS_Socket_fd
//Remote_Socket_fd
///

sem_init(
&sem_ss,0,0);
sem_init(
&sem_up,0,0);

while(1)
{
FD_ZERO(
&rset);
FD_SET(Local_UP_Socket_fd,
&rset);
FD_SET(Local_SS_Socket_fd,
&rset);
FD_SET(Remote_Socket_fd,
&rset);
maxfd
= max(Remote_Socket_fd,Local_SS_Socket_fd);
maxfd
= max(maxfd,Local_UP_Socket_fd);

if(select(maxfd+1,&rset,NULL,NULL,NULL) < 0)
{
if(errno == EINTR)
continue;
else
{
fprintf(stderr,
"Select error : %s\n",strerror(errno));
exit(
1);
}
}

if(FD_ISSET(Remote_Socket_fd,&rset))
{
printf(
"Remote Data/Cmd Recved\n");
}

if(FD_ISSET(Local_UP_Socket_fd,&rset))
{
if(pthread_create(&_local_up_thread,NULL,Client_TS_handle_up_local_data_cmd,(void *)&UPPara)!=0)
{
perror(
"Error Creating UP Thread");
}
else
{
sem_wait(
&sem_up);
}
}

if(FD_ISSET(Local_SS_Socket_fd,&rset))
{
if(pthread_create(&_local_ss_thread,NULL,Client_TS_handle_ss_local_data_cmd,(void *)&SSPara)!=0)
{
perror(
"Error Creating SS Thread");
}
else
{
sem_wait(
&sem_up);
}
}
}

close(Remote_Socket_fd);
close(Local_SS_Socket_fd);
close(Local_UP_Socket_fd);

sem_destroy(
&sem_up);
sem_destroy(
&sem_ss);
exit(
0);
}
/* End of File */

 

经过测试使用semaphore之后,虚拟内存控制下来了

posted on 2010-09-02 13:14  evander  阅读(281)  评论(0编辑  收藏  举报