dpdkgo語言 dpdk github

C語言等待一定時間輸入自動結(jié)束?

準備好linux編程環(huán)境,現(xiàn)場手撕定時器實現(xiàn)【linux服務(wù)器開發(fā)】

成都創(chuàng)新互聯(lián)公司-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比銅梁網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式銅梁網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋銅梁地區(qū)。費用合理售后完善,十余年實體公司更值得信賴。

工程師的圣地—Linux內(nèi)核, 談?wù)剝?nèi)核的架構(gòu)

c/c++ linux服務(wù)器開發(fā)學(xué)習(xí)地址:C/C++Linux服務(wù)器開發(fā)/后臺架構(gòu)師【零聲教育】-學(xué)習(xí)視頻教程-騰訊課堂

上圖是5個時間輪級聯(lián)的效果圖。中間的大輪是工作輪,只有在它上的任務(wù)才會被執(zhí)行;其他輪上的任務(wù)時間到后遷移到下一級輪上,他們最終都會遷移到工作輪上而被調(diào)度執(zhí)行。

多級時間輪的原理也容易理解:就拿時鐘做說明,秒針轉(zhuǎn)動一圈分針轉(zhuǎn)動一格;分針轉(zhuǎn)動一圈時針轉(zhuǎn)動一格;同理時間輪也是如此:當?shù)图壿嗈D(zhuǎn)動一圈時,高一級輪轉(zhuǎn)動一格,同時會將高一級輪上的任務(wù)重新分配到低級輪上。從而實現(xiàn)了多級輪級聯(lián)的效果。

1.1 多級時間輪對象

多級時間輪應(yīng)該至少包括以下內(nèi)容:

每一級時間輪對象

輪子上指針的位置

關(guān)于輪子上指針的位置有一個比較巧妙的辦法:那就是位運算。比如定義一個無符號整型的數(shù):

通過獲取當前的系統(tǒng)時間便可以通過位操作轉(zhuǎn)換為時間輪上的時間,通過與實際時間輪上的時間作比較,從而確定時間輪要前進調(diào)度的時間,進而操作對應(yīng)時間輪槽位對應(yīng)的任務(wù)。

為什么至少需要這兩個成員呢?

定義多級時間輪,首先需要明確的便是級聯(lián)的層數(shù),也就是說需要確定有幾個時間輪。

輪子上指針位置,就是當前時間輪運行到的位置,它與真實時間的差便是后續(xù)時間輪需要調(diào)度執(zhí)行,它們的差值是時間輪運作起來的驅(qū)動力。

多級時間輪對象的定義

//實現(xiàn)5級時間輪 范圍為0~ (2^8 * 2^6 * 2^6 * 2^6 *2^6)=2^32struct tvec_base{ unsigned long current_index; pthread_t thincrejiffies; pthread_t threadID; struct tvec_root tv1; /*第一個輪*/ struct tvec tv2; /*第二個輪*/ struct tvec tv3; /*第三個輪*/ struct tvec tv4; /*第四個輪*/ struct tvec tv5; /*第五個輪*/};

1.2 時間輪對象

我們知道每一個輪子實際上都是一個哈希表,上面我們只是實例化了五個輪子的對象,但是五個輪子具體包含什么,有幾個槽位等等沒有明確(即struct tvec和struct tvec_root)。

#define TVN_BITS 6#define TVR_BITS 8#define TVN_SIZE (1

此外,每一個時間輪都是哈希表,因此它的類型應(yīng)該至少包含兩個指針域來實現(xiàn)雙向鏈表的功能。這里我們?yōu)榱朔奖闶褂猛ㄓ玫膕truct list_head的雙向鏈表結(jié)構(gòu)。

1.3 定時任務(wù)對象

定時器的主要工作是為了在未來的特定時間完成某項任務(wù),而這個任務(wù)經(jīng)常包含以下內(nèi)容:

任務(wù)的處理邏輯(回調(diào)函數(shù))

任務(wù)的參數(shù)

雙向鏈表節(jié)點

到時時間

定時任務(wù)對象的定義

typedef void (*timeouthandle)(unsigned long ); struct timer_list{ struct list_head entry; //將時間連接成鏈表 unsigned long expires; //超時時間 void (*function)(unsigned long); //超時后的處理函數(shù) unsigned long data; //處理函數(shù)的參數(shù) struct tvec_base *base; //指向時間輪};

在時間輪上的效果圖:

【文章福利】需要C/C++ Linux服務(wù)器架構(gòu)師學(xué)習(xí)資料加群812855908(資料包括C/C++,Linux,golang技術(shù),內(nèi)核,Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒體,CDN,P2P,K8S,Docker,TCP/IP,協(xié)程,DPDK,ffmpeg等)

1.4 雙向鏈表

在時間輪上我們采用雙向鏈表的數(shù)據(jù)類型。采用雙向鏈表的除了操作上比單鏈表復(fù)雜,多占一個指針域外沒有其他不可接收的問題。而多占一個指針域在今天大內(nèi)存的時代明顯不是什么問題。至于雙向鏈表操作的復(fù)雜性,我們可以通過使用通用的struct list結(jié)構(gòu)來解決,因為雙向鏈表有眾多的標準操作函數(shù),我們可以通過直接引用list.h頭文件來使用他們提供的接口。

struct list可以說是一個萬能的雙向鏈表操作框架,我們只需要在自定義的結(jié)構(gòu)中定義一個struct list對象即可使用它的標準操作接口。同時它還提供了一個類似container_of的接口,在應(yīng)用層一般叫做list_entry,因此我們可以很方便的通過struct list成員找到自定義的結(jié)構(gòu)體的起始地址。

關(guān)于應(yīng)用層的log.h, 我將在下面的代碼中附上該文件。如果需要內(nèi)核層的實現(xiàn),可以直接從linux源碼中獲取。

1.5 聯(lián)結(jié)方式

多級時間輪效果圖:

二. 多級時間輪C語言實現(xiàn)

2.1 雙向鏈表頭文件: list.h

提到雙向鏈表,很多的源碼工程中都會實現(xiàn)一系列的統(tǒng)一的雙向鏈表操作函數(shù)。它們?yōu)殡p向鏈表封裝了統(tǒng)計的接口,使用者只需要在自定義的結(jié)構(gòu)中添加一個struct list_head結(jié)構(gòu),然后調(diào)用它們提供的接口,便可以完成雙向鏈表的所有操作。這些操作一般都在list.h的頭文件中實現(xiàn)。Linux源碼中也有實現(xiàn)(內(nèi)核態(tài)的實現(xiàn))。他們實現(xiàn)的方式基本完全一樣,只是實現(xiàn)的接口數(shù)量和功能上稍有差別。可以說這個list.h文件是學(xué)習(xí)操作雙向鏈表的不二選擇,它幾乎實現(xiàn)了所有的操作:增、刪、改、查、遍歷、替換、清空等等。這里我拼湊了一個源碼中的log.h函數(shù),終于湊夠了多級時間輪中使用到的接口。

#if !defined(_BLKID_LIST_H) !defined(LIST_HEAD)#define _BLKID_LIST_H#ifdef __cplusplus extern "C" {#endif/* * Simple doubly linked list implementation. * * Some of the internal functions ("__xxx") are useful when * manipulating whole lists rather than single entries, as * sometimes we already know the next/prev entries and we can * generate better code by using them directly rather than * using the generic single-entry routines. */struct list_head { struct list_head *next, *prev;};#define LIST_HEAD_INIT(name) { (name), (name) }#define LIST_HEAD(name) \ struct list_head name = LIST_HEAD_INIT(name)#define INIT_LIST_HEAD(ptr) do { \ (ptr)-next = (ptr); (ptr)-prev = (ptr); \} while (0)static inline void__list_add(struct list_head *entry, struct list_head *prev, struct list_head *next){ next-prev = entry; entry-next = next; entry-prev = prev; prev-next = entry;}/** * Insert a new element after the given list head. The new element does not * need to be initialised as empty list. * The list changes from: * head → some element → ... * to * head → new element → older element → ... * * Example: * struct foo *newfoo = malloc(...); * list_add(newfoo-entry, bar-list_of_foos); * * @param entry The new element to prepend to the list. * @param head The existing list. */static inline voidlist_add(struct list_head *entry, struct list_head *head){ __list_add(entry, head, head-next);}/** * Append a new element to the end of the list given with this list head. * * The list changes from: * head → some element → ... → lastelement * to * head → some element → ... → lastelement → new element * * Example: * struct foo *newfoo = malloc(...); * list_add_tail(newfoo-entry, bar-list_of_foos); * * @param entry The new element to prepend to the list. * @param head The existing list. */static inline voidlist_add_tail(struct list_head *entry, struct list_head *head){ __list_add(entry, head-prev, head);}static inline void__list_del(struct list_head *prev, struct list_head *next){ next-prev = prev; prev-next = next;}/** * Remove the element from the list it is in. Using this function will reset * the pointers to/from this element so it is removed from the list. It does * NOT free the element itself or manipulate it otherwise. * * Using list_del on a pure list head (like in the example at the top of * this file) will NOT remove the first element from * the list but rather reset the list as empty list. * * Example: * list_del(foo-entry); * * @param entry The element to remove. */static inline voidlist_del(struct list_head *entry){ __list_del(entry-prev, entry-next);}static inline voidlist_del_init(struct list_head *entry){ __list_del(entry-prev, entry-next); INIT_LIST_HEAD(entry);}static inline void list_move_tail(struct list_head *list, struct list_head *head){ __list_del(list-prev, list-next); list_add_tail(list, head);}/** * Check if the list is empty. * * Example: * list_empty(bar-list_of_foos); * * @return True if the list contains one or more elements or False otherwise. */static inline intlist_empty(struct list_head *head){ return head-next == head;}/** * list_replace - replace old entry by new one * @old : the element to be replaced * @new : the new element to insert * * If @old was empty, it will be overwritten. */static inline void list_replace(struct list_head *old, struct list_head *new){ new-next = old-next; new-next-prev = new; new-prev = old-prev; new-prev-next = new;}/** * Retrieve the first list entry for the given list pointer. * * Example: * struct foo *first; * first = list_first_entry(bar-list_of_foos, struct foo, list_of_foos); * * @param ptr The list head * @param type Data type of the list element to retrieve * @param member Member name of the struct list_head field in the list element. * @return A pointer to the first list element. */#define list_first_entry(ptr, type, member) \ list_entry((ptr)-next, type, member)static inline void list_replace_init(struct list_head *old, struct list_head *new){ list_replace(old, new); INIT_LIST_HEAD(old);}/** * list_entry - get the struct for this entry * @ptr: the struct list_head pointer. * @type: the type of the struct this is embedded in. * @member: the name of the list_struct within the struct. */#define list_entry(ptr, type, member) \ ((type *)((char *)(ptr)-(unsigned long)(((type *)0)-member)))/** * list_for_each - iterate over elements in a list * @pos: the struct list_head to use as a loop counter. * @head: the head for your list. */#define list_for_each(pos, head) \ for (pos = (head)-next; pos != (head); pos = pos-next)/** * list_for_each_safe - iterate over elements in a list, but don't dereference * pos after the body is done (in case it is freed) * @pos: the struct list_head to use as a loop counter. * @pnext: the struct list_head to use as a pointer to the next item. * @head: the head for your list (not included in iteration). */#define list_for_each_safe(pos, pnext, head) \ for (pos = (head)-next, pnext = pos-next; pos != (head); \ pos = pnext, pnext = pos-next)#ifdef __cplusplus}#endif#endif /* _BLKID_LIST_H */

這里面一般會用到一個重要實現(xiàn):container_of, 它的原理這里不敘述

2.2 調(diào)試信息頭文件: log.h

這個頭文件實際上不是必須的,我只是用它來添加調(diào)試信息(代碼中的errlog(), log()都是log.h中的宏函數(shù))。它的效果是給打印的信息加上顏色,效果如下:

log.h的代碼如下:

#ifndef _LOG_h_#define _LOG_h_#include #define COL(x) "\033[;" #x "m"#define RED COL(31)#define GREEN COL(32)#define YELLOW COL(33)#define BLUE COL(34)#define MAGENTA COL(35)#define CYAN COL(36)#define WHITE COL(0)#define GRAY "\033[0m"#define errlog(fmt, arg...) do{ \ printf(RED"[#ERROR: Toeny Sun:"GRAY YELLOW" %s:%d]:"GRAY WHITE fmt GRAY, __func__, __LINE__, ##arg);\}while(0)#define log(fmt, arg...) do{ \ printf(WHITE"[#DEBUG: Toeny Sun: "GRAY YELLOW"%s:%d]:"GRAY WHITE fmt GRAY, __func__, __LINE__, ##arg);\}while(0)#endif

2.3 時間輪代碼: timewheel.c

/* *毫秒定時器 采用多級時間輪方式 借鑒linux內(nèi)核中的實現(xiàn) *支持的范圍為1 ~ 2^32 毫秒(大約有49天) *若設(shè)置的定時器超過最大值 則按最大值設(shè)置定時器 **/#include #include #include #include #include #include #include "list.h"#include "log.h" #define TVN_BITS 6#define TVR_BITS 8#define TVN_SIZE (1current_index (TVR_BITS + (N) * TVN_BITS)) TVN_MASK) typedef void (*timeouthandle)(unsigned long ); struct timer_list{ struct list_head entry; //將時間連接成鏈表 unsigned long expires; //超時時間 void (*function)(unsigned long); //超時后的處理函數(shù) unsigned long data; //處理函數(shù)的參數(shù) struct tvec_base *base; //指向時間輪}; struct tvec { struct list_head vec[TVN_SIZE];}; struct tvec_root{ struct list_head vec[TVR_SIZE];}; //實現(xiàn)5級時間輪 范圍為0~ (2^8 * 2^6 * 2^6 * 2^6 *2^6)=2^32struct tvec_base{ unsigned long current_index; pthread_t thincrejiffies; pthread_t threadID; struct tvec_root tv1; /*第一個輪*/ struct tvec tv2; /*第二個輪*/ struct tvec tv3; /*第三個輪*/ struct tvec tv4; /*第四個輪*/ struct tvec tv5; /*第五個輪*/}; static void internal_add_timer(struct tvec_base *base, struct timer_list *timer){ struct list_head *vec; unsigned long expires = timer-expires; unsigned long idx = expires - base-current_index;#if 1 if( (signed long)idx 0 ) /*這里是沒有辦法區(qū)分出是過時還是超長定時的吧?*/ { vec = base-tv1.vec + (base-current_index TVR_MASK);/*放到第一個輪的當前槽*/ } else if ( idx TVR_SIZE ) /*第一個輪*/ { int i = expires TVR_MASK; vec = base-tv1.vec + i; } else if( idx 1 (TVR_BITS + TVN_BITS) )/*第二個輪*/ { int i = (expires TVR_BITS) TVN_MASK; vec = base-tv2.vec + i; } else if( idx 1 (TVR_BITS + 2 * TVN_BITS) )/*第三個輪*/ { int i = (expires (TVR_BITS + TVN_BITS)) TVN_MASK; vec = base-tv3.vec + i; } else if( idx 1 (TVR_BITS + 3 * TVN_BITS) )/*第四個輪*/ { int i = (expires (TVR_BITS + 2 * TVN_BITS)) TVN_MASK; vec = base-tv4.vec + i; } else /*第五個輪*/ { int i; if (idx 0xffffffffUL) { idx = 0xffffffffUL; expires = idx + base-current_index; } i = (expires (TVR_BITS + 3 * TVN_BITS)) TVN_MASK; vec = base-tv5.vec + i; }#else /*上面可以優(yōu)化吧*/;#endif list_add_tail(timer-entry, vec);} static inline void detach_timer(struct timer_list *timer){ struct list_head *entry = timer-entry; __list_del(entry-prev, entry-next); entry-next = NULL; entry-prev = NULL;} static int __mod_timer(struct timer_list *timer, unsigned long expires){ if(NULL != timer-entry.next) detach_timer(timer); internal_add_timer(timer-base, timer); return 0;} //修改定時器的超時時間外部接口int mod_timer(void *ptimer, unsigned long expires){ struct timer_list *timer = (struct timer_list *)ptimer; struct tvec_base *base; base = timer-base; if(NULL == base) return -1; expires = expires + base-current_index; if(timer-entry.next != NULL timer-expires == expires) return 0; if( NULL == timer-function ) { errlog("timer's timeout function is null\n"); return -1; } timer-expires = expires; return __mod_timer(timer,expires);} //添加一個定時器static void __ti_add_timer(struct timer_list *timer){ if( NULL != timer-entry.next ) { errlog("timer is already exist\n"); return; } mod_timer(timer, timer-expires); } /*添加一個定時器 外部接口 *返回定時器 */void* ti_add_timer(void *ptimewheel, unsigned long expires,timeouthandle phandle, unsigned long arg){ struct timer_list *ptimer; ptimer = (struct timer_list *)malloc( sizeof(struct timer_list) ); if(NULL == ptimer) return NULL; bzero( ptimer,sizeof(struct timer_list) ); ptimer-entry.next = NULL; ptimer-base = (struct tvec_base *)ptimewheel; ptimer-expires = expires; ptimer-function = phandle; ptimer-data = arg; __ti_add_timer(ptimer); return ptimer;} /* *刪除一個定時器 外部接口 * * */void ti_del_timer(void *p){ struct timer_list *ptimer =(struct timer_list*)p; if(NULL == ptimer) return; if(NULL != ptimer-entry.next) detach_timer(ptimer); free(ptimer);}/*時間輪級聯(lián)*/ static int cascade(struct tvec_base *base, struct tvec *tv, int index){ struct list_head *pos,*tmp; struct timer_list *timer; struct list_head tv_list; /*將tv[index]槽位上的所有任務(wù)轉(zhuǎn)移給tv_list,然后清空tv[index]*/ list_replace_init(tv-vec + index, tv_list);/*用tv_list替換tv-vec + index*/ list_for_each_safe(pos, tmp, tv_list)/*遍歷tv_list雙向鏈表,將任務(wù)重新添加到時間輪*/ { timer = list_entry(pos,struct timer_list,entry);/*struct timer_list中成員entry的地址是pos, 獲取struct timer_list的首地址*/ internal_add_timer(base, timer); } return index;} static void *deal_function_timeout(void *base){ struct timer_list *timer; int ret; struct timeval tv; struct tvec_base *ba = (struct tvec_base *)base; for(;;) { gettimeofday(tv, NULL); while( ba-current_index = (tv.tv_sec*1000 + tv.tv_usec/1000) )/*單位:ms*/ { struct list_head work_list; int index = ba-current_index TVR_MASK;/*獲取第一個輪上的指針位置*/ struct list_head *head = work_list; /*指針指向0槽時,級聯(lián)輪需要更新任務(wù)列表*/ if(!index (!cascade(ba, ba-tv2, INDEX(0))) ( !cascade(ba, ba-tv3, INDEX(1))) (!cascade(ba, ba-tv4, INDEX(2))) ) cascade(ba, ba-tv5, INDEX(3)); ba-current_index ++; list_replace_init(ba-tv1.vec + index, work_list); while(!list_empty(head)) { void (*fn)(unsigned long); unsigned long data; timer = list_first_entry(head, struct timer_list, entry); fn = timer-function; data = timer-data; detach_timer(timer); (*fn)(data); } } }} static void init_tvr_list(struct tvec_root * tvr){ int i; for( i = 0; ivec[i]);} static void init_tvn_list(struct tvec * tvn){ int i; for( i = 0; ivec[i]);} //創(chuàng)建時間輪 外部接口void *ti_timewheel_create(void ){ struct tvec_base *base; int ret = 0; struct timeval tv; base = (struct tvec_base *) malloc( sizeof(struct tvec_base) ); if( NULL==base ) return NULL; bzero( base,sizeof(struct tvec_base) ); init_tvr_list(base-tv1); init_tvn_list(base-tv2); init_tvn_list(base-tv3); init_tvn_list(base-tv4); init_tvn_list(base-tv5); gettimeofday(tv, NULL); base-current_index = tv.tv_sec*1000 + tv.tv_usec/1000;/*當前時間毫秒數(shù)*/ if( 0 != pthread_create(base-threadID,NULL,deal_function_timeout,base) ) { free(base); return NULL; } return base;} static void ti_release_tvr(struct tvec_root *pvr){ int i; struct list_head *pos,*tmp; struct timer_list *pen; for(i = 0; i TVR_SIZE; i++) { list_for_each_safe(pos,tmp,pvr-vec[i]) { pen = list_entry(pos,struct timer_list, entry); list_del(pos); free(pen); } }} static void ti_release_tvn(struct tvec *pvn){ int i; struct list_head *pos,*tmp; struct timer_list *pen; for(i = 0; i TVN_SIZE; i++) { list_for_each_safe(pos,tmp,pvn-vec[i]) { pen = list_entry(pos,struct timer_list, entry); list_del(pos); free(pen); } }} /* *釋放時間輪 外部接口 * */void ti_timewheel_release(void * pwheel){ struct tvec_base *base = (struct tvec_base *)pwheel; if(NULL == base) return; ti_release_tvr(base-tv1); ti_release_tvn(base-tv2); ti_release_tvn(base-tv3); ti_release_tvn(base-tv4); ti_release_tvn(base-tv5); free(pwheel);} /************demo****************/struct request_para{ void *timer; int val;}; void mytimer(unsigned long arg){ struct request_para *para = (struct request_para *)arg; log("%d\n",para-val); mod_timer(para-timer,3000); //進行再次啟動定時器 sleep(10);/*定時器依然被阻塞*/ //定時器資源的釋放是在這里完成的 //ti_del_timer(para-timer);} int main(int argc,char *argv[]){ void *pwheel = NULL; void *timer = NULL; struct request_para *para; para = (struct request_para *)malloc( sizeof(struct request_para) ); if(NULL == para) return 0; bzero(para,sizeof(struct request_para)); //創(chuàng)建一個時間輪 pwheel = ti_timewheel_create(); if(NULL == pwheel) return -1; //添加一個定時器 para-val = 100; para-timer = ti_add_timer(pwheel, 3000, mytimer, (unsigned long)para); while(1) { sleep(2); } //釋放時間輪 ti_timewheel_release(pwheel); return 0;}

2.4 編譯運行

toney@ubantu:/mnt/hgfs/em嵌入式學(xué)習(xí)記錄/4. timerwheel/2. 多級時間輪$ lsa.out list.h log.h mutiTimeWheel.ctoney@ubantu:/mnt/hgfs/em嵌入式學(xué)習(xí)記錄/4. timerwheel/2. 多級時間輪$ gcc mutiTimeWheel.c -lpthreadtoney@ubantu:/mnt/hgfs/em嵌入式學(xué)習(xí)記錄/4. timerwheel/2. 多級時間輪$ ./a.out [#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100[#DEBUG: Toeny Sun: mytimer:370]:100

從結(jié)果可以看出:如果添加的定時任務(wù)是比較耗時的操作,那么后續(xù)的任務(wù)也會被阻塞,可能一直到超時,甚至一直阻塞下去,這個取決于當前任務(wù)是否耗時。這個理論上是絕不能接受的:一個任務(wù)不應(yīng)該也不能去影響其他的任務(wù)吧。但是目前沒有對此問題進行改進和完善,以后有機會再繼續(xù)完善吧。

一篇搞懂tcp,http,socket,socket連接池之間的關(guān)系

作為一名開發(fā)人員我們經(jīng)常會聽到HTTP協(xié)議、TCP/IP協(xié)議、UDP協(xié)議、Socket、Socket長連接、Socket連接池等字眼,然而它們之間的關(guān)系、區(qū)別及原理并不是所有人都能理解清楚,這篇文章就從網(wǎng)絡(luò)協(xié)議基礎(chǔ)開始到Socket連接池,一步一步解釋他們之間的關(guān)系。

首先從網(wǎng)絡(luò)通信的分層模型講起:七層模型,亦稱OSI(Open System Interconnection)模型。自下往上分為:物理層、數(shù)據(jù)鏈路層、網(wǎng)絡(luò)層、傳輸層、會話層、表示層和應(yīng)用層。所有有關(guān)通信的都離不開它,下面這張圖片介紹了各層所對應(yīng)的一些協(xié)議和硬件

通過上圖,我知道IP協(xié)議對應(yīng)于網(wǎng)絡(luò)層,TCP、UDP協(xié)議對應(yīng)于傳輸層,而HTTP協(xié)議對應(yīng)于應(yīng)用層,OSI并沒有Socket,那什么是Socket,后面我們將結(jié)合代碼具體詳細介紹。

關(guān)于傳輸層TCP、UDP協(xié)議可能我們平時遇見的會比較多,有人說TCP是安全的,UDP是不安全的,UDP傳輸比TCP快,那為什么呢,我們先從TCP的連接建立的過程開始分析,然后解釋UDP和TCP的區(qū)別。

TCP的三次握手和四次分手

我們知道TCP建立連接需要經(jīng)過三次握手,而斷開連接需要經(jīng)過四次分手,那三次握手和四次分手分別做了什么和如何進行的。

第一次握手: 建立連接??蛻舳税l(fā)送連接請求報文段,將SYN位置為1,Sequence Number為x;然后,客戶端進入SYN_SEND狀態(tài),等待服務(wù)器的確認;

第二次握手: 服務(wù)器收到客戶端的SYN報文段,需要對這個SYN報文段進行確認,設(shè)置Acknowledgment Number為x+1(Sequence Number+1);同時,自己自己還要發(fā)送SYN請求信息,將SYN位置為1,Sequence Number為y;服務(wù)器端將上述所有信息放到一個報文段(即SYN+ACK報文段)中,一并發(fā)送給客戶端,此時服務(wù)器進入SYN_RECV狀態(tài);

第三次握手: 客戶端收到服務(wù)器的SYN+ACK報文段。然后將Acknowledgment Number設(shè)置為y+1,向服務(wù)器發(fā)送ACK報文段,這個報文段發(fā)送完畢以后,客戶端和服務(wù)器端都進入ESTABLISHED狀態(tài),完成TCP三次握手。

完成了三次握手,客戶端和服務(wù)器端就可以開始傳送數(shù)據(jù)。以上就是TCP三次握手的總體介紹。通信結(jié)束客戶端和服務(wù)端就斷開連接,需要經(jīng)過四次分手確認。

第一次分手: 主機1(可以使客戶端,也可以是服務(wù)器端),設(shè)置Sequence Number和Acknowledgment Number,向主機2發(fā)送一個FIN報文段;此時,主機1進入FIN_WAIT_1狀態(tài);這表示主機1沒有數(shù)據(jù)要發(fā)送給主機2了;

第二次分手: 主機2收到了主機1發(fā)送的FIN報文段,向主機1回一個ACK報文段,Acknowledgment Number為Sequence Number加1;主機1進入FIN_WAIT_2狀態(tài);主機2告訴主機1,我“同意”你的關(guān)閉請求;

第三次分手: 主機2向主機1發(fā)送FIN報文段,請求關(guān)閉連接,同時主機2進入LAST_ACK狀態(tài);

第四次分手 :主機1收到主機2發(fā)送的FIN報文段,向主機2發(fā)送ACK報文段,然后主機1進入TIME_WAIT狀態(tài);主機2收到主機1的ACK報文段以后,就關(guān)閉連接;此時,主機1等待2MSL后依然沒有收到回復(fù),則證明Server端已正常關(guān)閉,那好,主機1也可以關(guān)閉連接了。

可以看到一次tcp請求的建立及關(guān)閉至少進行7次通信,這還不包過數(shù)據(jù)的通信,而UDP不需3次握手和4次分手。

TCP和UDP的區(qū)別

 1、TCP是面向鏈接的,雖然說網(wǎng)絡(luò)的不安全不穩(wěn)定特性決定了多少次握手都不能保證連接的可靠性,但TCP的三次握手在最低限度上(實際上也很大程度上保證了)保證了連接的可靠性;而UDP不是面向連接的,UDP傳送數(shù)據(jù)前并不與對方建立連接,對接收到的數(shù)據(jù)也不發(fā)送確認信號,發(fā)送端不知道數(shù)據(jù)是否會正確接收,當然也不用重發(fā),所以說UDP是無連接的、不可靠的一種數(shù)據(jù)傳輸協(xié)議?!?/p>

 2、也正由于1所說的特點,使得UDP的開銷更小數(shù)據(jù)傳輸速率更高,因為不必進行收發(fā)數(shù)據(jù)的確認,所以UDP的實時性更好。知道了TCP和UDP的區(qū)別,就不難理解為何采用TCP傳輸協(xié)議的MSN比采用UDP的QQ傳輸文件慢了,但并不能說QQ的通信是不安全的,因為程序員可以手動對UDP的數(shù)據(jù)收發(fā)進行驗證,比如發(fā)送方對每個數(shù)據(jù)包進行編號然后由接收方進行驗證啊什么的,即使是這樣,UDP因為在底層協(xié)議的封裝上沒有采用類似TCP的“三次握手”而實現(xiàn)了TCP所無法達到的傳輸效率。

關(guān)于傳輸層我們會經(jīng)常聽到一些問題

1.TCP服務(wù)器最大并發(fā)連接數(shù)是多少?

關(guān)于TCP服務(wù)器最大并發(fā)連接數(shù)有一種誤解就是“因為端口號上限為65535,所以TCP服務(wù)器理論上的可承載的最大并發(fā)連接數(shù)也是65535”。首先需要理解一條TCP連接的組成部分: 客戶端IP、客戶端端口、服務(wù)端IP、服務(wù)端端口 。所以對于TCP服務(wù)端進程來說,他可以同時連接的客戶端數(shù)量并不受限于可用端口號,理論上一個服務(wù)器的一個端口能建立的連接數(shù)是全球的IP數(shù)*每臺機器的端口數(shù)。實際并發(fā)連接數(shù)受限于linux可打開文件數(shù),這個數(shù)是可以配置的,可以非常大,所以實際上受限于系統(tǒng)性能。通過#ulimit -n 查看服務(wù)的最大文件句柄數(shù),通過ulimit -n xxx 修改 xxx是你想要能打開的數(shù)量。也可以通過修改系統(tǒng)參數(shù):

2.為什么TIME_WAIT狀態(tài)還需要等2MSL后才能返回到CLOSED狀態(tài)?

這是因為雖然雙方都同意關(guān)閉連接了,而且握手的4個報文也都協(xié)調(diào)和發(fā)送完畢,按理可以直接回到CLOSED狀態(tài)(就好比從SYN_SEND狀態(tài)到ESTABLISH狀態(tài)那樣);但是因為我們必須要假想網(wǎng)絡(luò)是不可靠的,你無法保證你最后發(fā)送的ACK報文會一定被對方收到,因此對方處于LAST_ACK狀態(tài)下的Socket可能會因為超時未收到ACK報文,而重發(fā)FIN報文,所以這個TIME_WAIT狀態(tài)的作用就是用來重發(fā)可能丟失的ACK報文。

3.TIME_WAIT狀態(tài)還需要等2MSL后才能返回到CLOSED狀態(tài)會產(chǎn)生什么問題

通信雙方建立TCP連接后,主動關(guān)閉連接的一方就會進入TIME_WAIT狀態(tài),TIME_WAIT狀態(tài)維持時間是兩個MSL時間長度,也就是在1-4分鐘,Windows操作系統(tǒng)就是4分鐘。進入TIME_WAIT狀態(tài)的一般情況下是客戶端,一個TIME_WAIT狀態(tài)的連接就占用了一個本地端口。一臺機器上端口號數(shù)量的上限是65536個,如果在同一臺機器上進行壓力測試模擬上萬的客戶請求,并且循環(huán)與服務(wù)端進行短連接通信,那么這臺機器將產(chǎn)生4000個左右的TIME_WAIT Socket,后續(xù)的短連接就會產(chǎn)生address already in use : connect的異常,如果使用Nginx作為方向代理也需要考慮TIME_WAIT狀態(tài),發(fā)現(xiàn)系統(tǒng)存在大量TIME_WAIT狀態(tài)的連接,通過調(diào)整內(nèi)核參數(shù)解決。

編輯文件,加入以下內(nèi)容:

然后執(zhí)行 /sbin/sysctl -p 讓參數(shù)生效。

net.ipv4.tcp_syncookies = 1 表示開啟SYN Cookies。當出現(xiàn)SYN等待隊列溢出時,啟用cookies來處理,可防范少量SYN攻擊,默認為0,表示關(guān)閉;

net.ipv4.tcp_tw_reuse = 1 表示開啟重用。允許將TIME-WAIT sockets重新用于新的TCP連接,默認為0,表示關(guān)閉;

net.ipv4.tcp_tw_recycle = 1 表示開啟TCP連接中TIME-WAIT sockets的快速回收,默認為0,表示關(guān)閉。

net.ipv4.tcp_fin_timeout 修改系統(tǒng)默認的TIMEOUT時間

相關(guān)視頻推薦

10道網(wǎng)絡(luò)八股文,每道都很經(jīng)典,讓你在面試中逼格滿滿

徒手實現(xiàn)網(wǎng)絡(luò)協(xié)議棧,請準備好環(huán)境,一起來寫代碼

學(xué)習(xí)地址:C/C++Linux服務(wù)器開發(fā)/后臺架構(gòu)師【零聲教育】-學(xué)習(xí)視頻教程-騰訊課堂

需要C/C++ Linux服務(wù)器架構(gòu)師學(xué)習(xí)資料加qun812855908獲?。ㄙY料包括 C/C++,Linux,golang技術(shù),Nginx,ZeroMQ,MySQL,Redis,fastdfs,MongoDB,ZK,流媒體,CDN,P2P,K8S,Docker,TCP/IP,協(xié)程,DPDK,ffmpeg 等),免費分享

關(guān)于TCP/IP和HTTP協(xié)議的關(guān)系,網(wǎng)絡(luò)有一段比較容易理解的介紹:“我們在傳輸數(shù)據(jù)時,可以只使用(傳輸層)TCP/IP協(xié)議,但是那樣的話,如果沒有應(yīng)用層,便無法識別數(shù)據(jù)內(nèi)容。如果想要使傳輸?shù)臄?shù)據(jù)有意義,則必須使用到應(yīng)用層協(xié)議。應(yīng)用層協(xié)議有很多,比如HTTP、FTP、TELNET等,也可以自己定義應(yīng)用層協(xié)議。

HTTP協(xié)議即超文本傳送協(xié)議(Hypertext Transfer Protocol ),是Web聯(lián)網(wǎng)的基礎(chǔ),也是手機聯(lián)網(wǎng)常用的協(xié)議之一,WEB使用HTTP協(xié)議作應(yīng)用層協(xié)議,以封裝HTTP文本信息,然后使用TCP/IP做傳輸層協(xié)議將它發(fā)到網(wǎng)絡(luò)上。

由于HTTP在每次請求結(jié)束后都會主動釋放連接,因此HTTP連接是一種“短連接”,要保持客戶端程序的在線狀態(tài),需要不斷地向服務(wù)器發(fā)起連接請求。通常 的做法是即時不需要獲得任何數(shù)據(jù),客戶端也保持每隔一段固定的時間向服務(wù)器發(fā)送一次“保持連接”的請求,服務(wù)器在收到該請求后對客戶端進行回復(fù),表明知道 客戶端“在線”。若服務(wù)器長時間無法收到客戶端的請求,則認為客戶端“下線”,若客戶端長時間無法收到服務(wù)器的回復(fù),則認為網(wǎng)絡(luò)已經(jīng)斷開。

下面是一個簡單的HTTP Post application/json數(shù)據(jù)內(nèi)容的請求:

現(xiàn)在我們了解到TCP/IP只是一個協(xié)議棧,就像操作系統(tǒng)的運行機制一樣,必須要具體實現(xiàn),同時還要提供對外的操作接口。就像操作系統(tǒng)會提供標準的編程接口,比如Win32編程接口一樣,TCP/IP也必須對外提供編程接口,這就是Socket?,F(xiàn)在我們知道,Socket跟TCP/IP并沒有必然的聯(lián)系。Socket編程接口在設(shè)計的時候,就希望也能適應(yīng)其他的網(wǎng)絡(luò)協(xié)議。所以,Socket的出現(xiàn)只是可以更方便的使用TCP/IP協(xié)議棧而已,其對TCP/IP進行了抽象,形成了幾個最基本的函數(shù)接口。比如create,listen,accept,connect,read和write等等。

不同語言都有對應(yīng)的建立Socket服務(wù)端和客戶端的庫,下面舉例Nodejs如何創(chuàng)建服務(wù)端和客戶端:

服務(wù)端:

服務(wù)監(jiān)聽9000端口

下面使用命令行發(fā)送http請求和telnet

注意到curl只處理了一次報文。

客戶端

Socket長連接

所謂長連接,指在一個TCP連接上可以連續(xù)發(fā)送多個數(shù)據(jù)包,在TCP連接保持期間,如果沒有數(shù)據(jù)包發(fā)送,需要雙方發(fā)檢測包以維持此連接(心跳包),一般需要自己做在線維持。 短連接是指通信雙方有數(shù)據(jù)交互時,就建立一個TCP連接,數(shù)據(jù)發(fā)送完成后,則斷開此TCP連接。比如Http的,只是連接、請求、關(guān)閉,過程時間較短,服務(wù)器若是一段時間內(nèi)沒有收到請求即可關(guān)閉連接。其實長連接是相對于通常的短連接而說的,也就是長時間保持客戶端與服務(wù)端的連接狀態(tài)。

通常的短連接操作步驟是:

連接 數(shù)據(jù)傳輸 關(guān)閉連接;

而長連接通常就是:

連接 數(shù)據(jù)傳輸 保持連接(心跳) 數(shù)據(jù)傳輸 保持連接(心跳) …… 關(guān)閉連接;

什么時候用長連接,短連接?

長連接多用于操作頻繁,點對點的通訊,而且連接數(shù)不能太多情況,。每個TCP連接都需要三步握手,這需要時間,如果每個操作都是先連接,再操作的話那么處理 速度會降低很多,所以每個操作完后都不斷開,次處理時直接發(fā)送數(shù)據(jù)包就OK了,不用建立TCP連接。例如:數(shù)據(jù)庫的連接用長連接, 如果用短連接頻繁的通信會造成Socket錯誤,而且頻繁的Socket創(chuàng)建也是對資源的浪費。

什么是心跳包為什么需要:

心跳包就是在客戶端和服務(wù)端間定時通知對方自己狀態(tài)的一個自己定義的命令字,按照一定的時間間隔發(fā)送,類似于心跳,所以叫做心跳包。網(wǎng)絡(luò)中的接收和發(fā)送數(shù)據(jù)都是使用Socket進行實現(xiàn)。但是如果此套接字已經(jīng)斷開(比如一方斷網(wǎng)了),那發(fā)送數(shù)據(jù)和接收數(shù)據(jù)的時候就一定會有問題??墒侨绾闻袛噙@個套接字是否還可以使用呢?這個就需要在系統(tǒng)中創(chuàng)建心跳機制。其實TCP中已經(jīng)為我們實現(xiàn)了一個叫做心跳的機制。如果你設(shè)置了心跳,那TCP就會在一定的時間(比如你設(shè)置的是3秒鐘)內(nèi)發(fā)送你設(shè)置的次數(shù)的心跳(比如說2次),并且此信息不會影響你自己定義的協(xié)議。也可以自己定義,所謂“心跳”就是定時發(fā)送一個自定義的結(jié)構(gòu)體(心跳包或心跳幀),讓對方知道自己“在線”,以確保鏈接的有效性。

實現(xiàn):

服務(wù)端:

服務(wù)端輸出結(jié)果:

客戶端代碼:

客戶端輸出結(jié)果:

如果想要使傳輸?shù)臄?shù)據(jù)有意義,則必須使用到應(yīng)用層協(xié)議比如Http、Mqtt、Dubbo等?;赥CP協(xié)議上自定義自己的應(yīng)用層的協(xié)議需要解決的幾個問題:

下面我們就一起來定義自己的協(xié)議,并編寫服務(wù)的和客戶端進行調(diào)用:

定義報文頭格式: length:000000000xxxx; xxxx代表數(shù)據(jù)的長度,總長度20,舉例子不嚴謹。

數(shù)據(jù)表的格式: Json

服務(wù)端:

日志打?。?/p>

客戶端

日志打印:

客戶端定時發(fā)送自定義協(xié)議數(shù)據(jù)到服務(wù)端,先發(fā)送頭數(shù)據(jù),在發(fā)送內(nèi)容數(shù)據(jù),另外一個定時器發(fā)送心跳數(shù)據(jù),服務(wù)端判斷是心跳數(shù)據(jù),再判斷是不是頭數(shù)據(jù),再是內(nèi)容數(shù)據(jù),然后解析后再發(fā)送數(shù)據(jù)給客戶端。從日志的打印可以看出客戶端先后writeheader和data數(shù)據(jù),服務(wù)端可能在一個data事件里面接收到。

這里可以看到一個客戶端在同一個時間內(nèi)處理一個請求可以很好的工作,但是想象這么一個場景,如果同一時間內(nèi)讓同一個客戶端去多次調(diào)用服務(wù)端請求,發(fā)送多次頭數(shù)據(jù)和內(nèi)容數(shù)據(jù),服務(wù)端的data事件收到的數(shù)據(jù)就很難區(qū)別哪些數(shù)據(jù)是哪次請求的,比如兩次頭數(shù)據(jù)同時到達服務(wù)端,服務(wù)端就會忽略其中一次,而后面的內(nèi)容數(shù)據(jù)也不一定就對應(yīng)于這個頭的。所以想復(fù)用長連接并能很好的高并發(fā)處理服務(wù)端請求,就需要連接池這種方式了。

什么是Socket連接池,池的概念可以聯(lián)想到是一種資源的集合,所以Socket連接池,就是維護著一定數(shù)量Socket長連接的集合。它能自動檢測Socket長連接的有效性,剔除無效的連接,補充連接池的長連接的數(shù)量。從代碼層次上其實是人為實現(xiàn)這種功能的類,一般一個連接池包含下面幾個屬性:

場景: 一個請求過來,首先去資源池要求獲取一個長連接資源,如果空閑隊列里面有長連接,就獲取到這個長連接Socket,并把這個Socket移到正在運行的長連接隊列。如果空閑隊列里面沒有,且正在運行的隊列長度小于配置的連接池資源的數(shù)量,就新建一個長連接到正在運行的隊列去,如果正在運行的不下于配置的資源池長度,則這個請求進入到等待隊列去。當一個正在運行的Socket完成了請求,就從正在運行的隊列移到空閑的隊列,并觸發(fā)等待請求隊列去獲取空閑資源,如果有等待的情況。

這里簡單介紹Nodejs的Socket連接池generic-pool模塊的源碼。

主要文件目錄結(jié)構(gòu)

下面介紹庫的使用:

初始化連接池

使用連接池

下面連接池的使用,使用的協(xié)議是我們之前自定義的協(xié)議。

日志打印:

這里看到前面兩個請求都建立了新的Socket連接 socket_pool 127.0.0.1 9000 connect,定時器結(jié)束后重新發(fā)起兩個請求就沒有建立新的Socket連接了,直接從連接池里面獲取Socket連接資源。

源碼分析

發(fā)現(xiàn)主要的代碼就位于lib文件夾中的Pool.js

構(gòu)造函數(shù):

lib/Pool.js

可以看到包含之前說的空閑的資源隊列,正在請求的資源隊列,正在等待的請求隊列等。

下面查看 Pool.acquire 方法

lib/Pool.js

上面的代碼就按種情況一直走下到最終獲取到長連接的資源,其他更多代碼大家可以自己去深入了解。

網(wǎng)站欄目:dpdkgo語言 dpdk github
分享路徑:http://muchs.cn/article10/doeiedo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供關(guān)鍵詞優(yōu)化網(wǎng)頁設(shè)計公司、定制網(wǎng)站、云服務(wù)器、網(wǎng)站制作建站公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)