2017-10-04 184 views
0

我正在處理通過API接收請求並將其添加到FIFO的項目。我希望能夠記錄收到的請求數(添加到隊列中)和處理的請求數(從隊列中刪除)。目前我正在嘗試收到第二個平均值。計算每秒添加到隊列的請求數 - 總是返回爲零

我這樣做是通過一個包含60個元素的long數組來完成的,每個元素將存儲在那秒接收到的請求的數量。

我使用以下這樣:

if (fifo->enqueue(crashInfo)) 
    { 
     this->requestProcessMutex.lock(); 
     this->currentRequestsASecond++; //Used to get the total requests a second 
     this->requestProcessMutex.unlock(); 
     cout << "Current Requests Incremented to " << this->currentRequestsASecond << endl; 
     return true; 
    } 
    else 
    { 
     return false; 
    } 

從上面的代碼的COUT是表示計數器遞增,然後復位爲0作爲預期每個第二。

要將請求每秒添加到數組中,我執行以下操作,我還每10秒註銷一次當前平均值。

void FIFOManager::processRequestsSecondArray() 
{ 
    int counter = 0; 
    time_t lastLoggedTime = std::time(NULL); 
    while (this->bitsLibrary->getApplicationStatus() != StatusManager::ApplicationStatus::Stopping) 
    { 

     this->requestProcessMutex.lock(); 
     time_t current_time = std::time(NULL); 
     long timeDiff = current_time - lastLoggedTime; 
     if (timeDiff >= 10) //Only log every 10 seconds 
     { 
      stringstream logstream; 
      logstream << this->getAverageRequestProcessTime(AverageRetrievalType::RequestsASec) << " requests received a second"; 
      this->bitsLibrary->writeToLog(logstream.str(), "FIFOManager", "processRequestsSecondArray"); 
      lastLoggedTime = std::time(NULL); 
     } 
     requestsASecondForAMinute[counter] = this->currentRequestsASecond; 

     cout << "ADDING REQUEST COUNTER VALUE " << this->currentRequestsASecond << " AT " << counter << endl; 
     if (counter < 59) 
     { 
      counter++; 
     } 
     else 
     { 
      counter = 0; //Only storing a minutes worth (60 secondS) so reset and start to overwrite 
     } 
     this->requestProcessMutex.unlock(); 
     this_thread::sleep_for(chrono::seconds(1)); 
     this->requestProcessMutex.lock(); 
     this->currentRequestsASecond = 0; 
     this->requestProcessMutex.unlock(); 
    } 
} 

processRequestsSecondArray是在陣列休眠1秒,在每一個第二應在當前的第二元件的currentRequestsASecond的值存儲到所述陣列,它包裝每分鐘,並通過在陣列覆蓋。

ADDING REQUEST COUNTER VALUE的輸出始終表明它正在添加0currentRequestsASecond不會重置爲0,直到發生睡眠之後,我做錯了什麼?

回答

1

processRequestsSecondArray()功能看起來會做這一次,第二:

  1. 喚醒從sleep_for()電話。

  2. currentRequestsASecond設置爲零。

  3. 返回while循環的頂部。

  4. 可能計算並打印出陣列的平均值。

  5. 店面currentRequestsASecondrequestsASecondForAMinute的元素。

  6. 再次致電sleep_for()

看到問題了嗎?

sleep_for()時間內對currentRequestsASecond所做的任何更改都將被清除,並且不會放入數組中。如果增量足夠幸運地發生請求並在可能很短的時間內獲取互斥鎖,那麼只會獲得一個值processRequestsSecondArray()解鎖互斥鎖,檢查getApplicationStatus(),並立即再次鎖定互斥鎖。看起來你需要重新安排一些邏輯。

+0

Duh現在非常明顯,盯着它已經很久沒有看到它了。在將循環計數器插入數組後,我將循環中的計數器復位移至0。謝謝你的幫助 – Boardy