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