本文實例講述了C++數(shù)據(jù)結(jié)構(gòu)與算法之雙緩存隊列實現(xiàn)方法。分享給大家供大家參考,具體如下:
“雙緩存隊列”是我在一次開發(fā)任務(wù)中針對特殊場景設(shè)計出來的結(jié)構(gòu)。使用場景為:發(fā)送端持續(xù)向接收端發(fā)送數(shù)據(jù)包――并且不理會接收端是否完成業(yè)務(wù)邏輯。由于接收端在任何情況下停止響應(yīng)即可能產(chǎn)生數(shù)據(jù)丟失,因此無法簡單的設(shè)計一條線程安全隊列來對數(shù)據(jù)寫入或讀取(讀取數(shù)據(jù)時將隊列上鎖視為對寫入的停止響應(yīng))。
鑒于此,我的設(shè)計思路如下:

接收端首先向A隊列中寫入數(shù)據(jù),然后當(dāng)數(shù)據(jù)處理請求到來的時候切換到B隊列繼續(xù)寫入,之后將A隊列中的數(shù)據(jù)交給數(shù)據(jù)處理模塊,處理完成以后A隊列數(shù)據(jù)清空。當(dāng)下一次數(shù)據(jù)處理請求到來時,再將寫入請求切換回A隊列,并把B隊列中的數(shù)據(jù)提交給數(shù)據(jù)處理模塊再清空隊列B,輪流作業(yè)。
有了思路以后,代碼就比較簡單了。
#include <list>template<typename T>class DoubleArray {  struct NODE {    T t;    NODE* next;  };  int size_a;  int size_b;  NODE* header_a;  NODE* header_a_cur;  NODE* header_b;  NODE* header_b_cur;  int trigger;public:  DoubleArray() : size_a(0), size_b(0), trigger(0), header_a(0), header_a_cur(0), header_b(0), header_b_cur(0) {  }  int push(T t);  std::list<T>& fetch(std::list<T>& list);};template<typename T>int DoubleArray<T>::push(T t) {  NODE *n = new NODE;  n->t = t;  n->next = 0;  if (size_a == 0 && trigger == 0) {    header_a = n;    header_a_cur = n;    size_a++;  } else if (size_b == 0 && trigger == 1) {    header_b = n;    header_b_cur = n;    size_b++;  } else {    switch (trigger) {      case 0:        header_a_cur->next = n;        header_a_cur = n;        size_a++;        break;      case 1:        header_b_cur->next = n;        header_b_cur = n;        size_b++;        break;    }  }}template<typename T>std::list<T>& DoubleArray<T>::fetch(std::list<T>& list) {  switch (trigger) {    case 0:      if (header_a != 0) {        // change b        trigger = 1;        // fetch a        NODE* temp = header_a;        while (temp) {          list.push_back(temp->t);          temp = temp->next;        }        // delete a        temp = header_a;        for (int i = 0; i < size_a; ++i) {          NODE* p = temp;          temp = temp->next;          delete p;        }        size_a = 0;        header_a = 0;        header_a_cur = 0;      }      break;    case 1:      if (header_b != 0) {        // change a        trigger = 0;        // fetch b        NODE* temp = header_b;        // delete b        while (temp) {          list.push_back(temp->t);          temp = temp->next;        }        temp = header_b;        for (int i = 0; i < size_b; ++i) {          NODE* p = temp;          temp = temp->next;          delete p;        }        size_b = 0;        header_b = 0;        header_b_cur = 0;      }      break;  }  return list;}注:開發(fā)環(huán)境與IDE分別為CentOS 7,NetBeans 8.2
希望本文所述對大家C++程序設(shè)計有所幫助。
新聞熱點
疑難解答