cpu-usage: reduce cpu usage when idle

This commit is contained in:
Nick Peng
2022-10-27 21:38:04 +08:00
parent 391ef310b4
commit 7b8ff57773
4 changed files with 209 additions and 13 deletions

View File

@@ -184,8 +184,8 @@ struct dns_client {
int ssl_verify_skip;
/* query list */
pthread_mutex_t dns_request_lock;
struct list_head dns_request_list;
pthread_cond_t run_cond;
atomic_t dns_server_num;
/* ECS */
@@ -3129,6 +3129,10 @@ int dns_client_query(const char *domain, int qtype, dns_client_callback callback
}
pthread_mutex_lock(&client.domain_map_lock);
if (list_empty(&client.dns_request_list)) {
pthread_cond_signal(&client.run_cond);
}
list_add_tail(&query->dns_request_list, &client.dns_request_list);
pthread_mutex_unlock(&client.domain_map_lock);
@@ -3402,15 +3406,25 @@ static void *_dns_client_work(void *arg)
int num = 0;
int i = 0;
unsigned long now = {0};
unsigned long last = {0};
unsigned int sleep = 100;
int sleep_time = 0;
unsigned long expect_time = 0;
sleep_time = sleep;
now = get_tick_count() - sleep;
last = now;
expect_time = now + sleep;
while (atomic_read(&client.run)) {
now = get_tick_count();
if (sleep_time > 0) {
sleep_time -= now - last;
if (sleep_time <= 0) {
sleep_time = 0;
}
}
last = now;
if (now >= expect_time) {
_dns_client_period_run();
sleep_time = sleep - (now - expect_time);
@@ -3421,6 +3435,15 @@ static void *_dns_client_work(void *arg)
expect_time += sleep;
}
pthread_mutex_lock(&client.domain_map_lock);
if (list_empty(&client.dns_request_list)) {
pthread_cond_wait(&client.run_cond, &client.domain_map_lock);
expect_time = get_tick_count();
pthread_mutex_unlock(&client.domain_map_lock);
continue;
}
pthread_mutex_unlock(&client.domain_map_lock);
num = epoll_wait(client.epoll_fd, events, DNS_MAX_EVENTS, sleep_time);
if (num < 0) {
usleep(100000);
@@ -3511,6 +3534,8 @@ int dns_client_init(void)
hash_init(client.group);
INIT_LIST_HEAD(&client.dns_request_list);
pthread_cond_init(&client.run_cond, NULL);
if (dns_client_add_group(DNS_SERVER_GROUP_DEFAULT) != 0) {
tlog(TLOG_ERROR, "add default server group failed.");
goto errout;
@@ -3542,6 +3567,7 @@ errout:
pthread_mutex_destroy(&client.server_list_lock);
pthread_mutex_destroy(&client.domain_map_lock);
pthread_cond_destroy(&client.run_cond);
return -1;
}
@@ -3551,6 +3577,9 @@ void dns_client_exit(void)
if (client.tid) {
void *ret = NULL;
atomic_set(&client.run, 0);
pthread_mutex_lock(&client.domain_map_lock);
pthread_cond_signal(&client.run_cond);
pthread_mutex_unlock(&client.domain_map_lock);
pthread_join(client.tid, &ret);
client.tid = 0;
}
@@ -3563,6 +3592,7 @@ void dns_client_exit(void)
pthread_mutex_destroy(&client.server_list_lock);
pthread_mutex_destroy(&client.domain_map_lock);
pthread_cond_destroy(&client.run_cond);
if (client.ssl_ctx) {
SSL_CTX_free(client.ssl_ctx);
client.ssl_ctx = NULL;