reduce cpu usage using semaphore

This commit is contained in:
lxsang
2018-10-10 12:42:47 +02:00
parent d60109fcf9
commit 592fc88587
3 changed files with 93 additions and 27 deletions

32
httpd.c
View File

@ -95,7 +95,8 @@ void stop_serve(int dummy) {
ERR_remove_state(0);
ERR_free_strings();
#endif
close(server_sock);
if(server_sock != -1)
close(server_sock);
sigprocmask(SIG_UNBLOCK, &mask, NULL);
}
int main(int argc, char* argv[])
@ -130,23 +131,28 @@ int main(int argc, char* argv[])
LOG("httpd running on port %d\n", port);
// default to 4 workers
antd_scheduler_init(&scheduler, config()->n_workers);
set_nonblock(server_sock);
int stat = 0;
struct timespec ts_sleep;
// use blocking server_sock
// make the scheduler wait for event on another thread
// this allow to ged rid of high cpu usage on
// endless loop without doing anything
// set_nonblock(server_sock);
pthread_t scheduler_th;
if (pthread_create(&scheduler_th, NULL,(void *(*)(void *))antd_wait, (void*)&scheduler) != 0)
{
perror("pthread_create: cannot create worker\n");
stop_serve(0);
exit(1);
}
else
{
// reclaim data when exit
pthread_detach(scheduler_th);
}
while (scheduler.status)
{
stat = antd_task_schedule(&scheduler);
client_sock = accept(server_sock,(struct sockaddr *)&client_name,&client_name_len);
if (client_sock == -1)
{
if(!stat)
{
// sleep for 500usec if
// there is nothing todo
ts_sleep.tv_sec = 0;
ts_sleep.tv_nsec = 500000;
nanosleep(&ts_sleep, NULL);
}
continue;
}
antd_client_t* client = (antd_client_t*)malloc(sizeof(antd_client_t));