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

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

修改后的代码如下

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
///
// 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之后,虚拟内存控制下来了

转载于:https://www.cnblogs.com/eavn/archive/2010/09/02/1815927.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值