在多线程并发请求Api的场景中,如何控制每个线程的qps

想了一段时间,给出代码Demo

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h> typedef struct qps_s{
int count;
unsigned int second;
}qps_t; pthread_key_t tdata;
qps_t qps_data; int push_timestamp() {
time_t tt;
return time(&tt);
} void *thread_data_del(void *tdata){
if(tdata){
free(tdata);
printf("free\n");
}
} void doing(){
qps_t *qps_data = (qps_t *)pthread_getspecific(tdata);
//说明还没有设置过
if(!qps_data){
qps_data = (qps_t *)calloc(, sizeof(qps_t));
qps_data->count = ;
qps_data->second = push_timestamp();
pthread_setspecific(tdata, qps_data);
} while(){
int now_time = push_timestamp();
if(now_time == qps_data->second){
//触发了qps限制
if(qps_data->count >= ){
usleep();
continue;
}
//没有触发限制
else{
qps_data->count++;
break;
}
}else{
//时间不相同,说明qps限制肯定没问题
qps_data->count = ;
qps_data->second = now_time;
break;
} }
printf("request some api => %d, %d\n", qps_data->second, qps_data->count);
} void *worker(void *argv){
int i;
for(i = ; i < ; i++){
doing();
}
} int main(){
pthread_t pid1, pid2;
pthread_key_create(&tdata, (void *)(void *)thread_data_del); pthread_create(&pid1, NULL, worker, NULL); pthread_join(pid1, NULL);
pthread_key_delete(tdata);
return ;
}

效果

[work@dev news_push/]valgrind --tool=memcheck ./a.out
==== Memcheck, a memory error detector
==== Copyright (C) -, and GNU GPL'd, by Julian Seward et al.
==== Using Valgrind-3.10. and LibVEX; rerun with -h for copyright info
==== Command: ./a.out
====
request some api => ,
request some api => ,
request some api => ,
request some api => ,
request some api => ,
request some api => ,
request some api => ,
request some api => ,
request some api => ,
request some api => ,
free
====
==== HEAP SUMMARY:
==== in use at exit: bytes in blocks
==== total heap usage: allocs, frees, bytes allocated
====
==== All heap blocks were freed -- no leaks are possible
====
==== For counts of detected and suppressed errors, rerun with: -v
==== ERROR SUMMARY: errors from contexts (suppressed: from )
上一篇:五分钟入门 Dingo API


下一篇:laravel Passport - Dingo/Api v2.0+Passport 实现 api 认证