Skip to content

Commit

Permalink
Merge pull request ddnet#9145 from Robyt3/Http-Request-Wait-Condition
Browse files Browse the repository at this point in the history
Avoid busy waiting in `CHttpRequest::Wait` function
  • Loading branch information
def- authored Oct 13, 2024
2 parents 34015ea + ad8349b commit a397688
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 11 deletions.
17 changes: 6 additions & 11 deletions src/engine/shared/http.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ void CHttpRequest::OnCompletionInternal(void *pHandle, unsigned int Result)
// before the result has been initialized/updated in OnCompletion.
OnCompletion(State);
m_State = State;
m_WaitCondition.notify_all();
}

void CHttpRequest::WriteToFile(IStorage *pStorage, const char *pDest, int StorageType)
Expand All @@ -402,18 +403,11 @@ void CHttpRequest::Header(const char *pNameColonValue)

void CHttpRequest::Wait()
{
using namespace std::chrono_literals;

// This is so uncommon that polling just might work
for(;;)
{
std::unique_lock Lock(m_WaitMutex);
m_WaitCondition.wait(Lock, [this]() {
EHttpState State = m_State.load(std::memory_order_seq_cst);
if(State != EHttpState::QUEUED && State != EHttpState::RUNNING)
{
return;
}
std::this_thread::sleep_for(10ms);
}
return State != EHttpState::QUEUED && State != EHttpState::RUNNING;
});
}

void CHttpRequest::Result(unsigned char **ppResult, size_t *pResultLength) const
Expand Down Expand Up @@ -604,6 +598,7 @@ void CHttp::RunLoop()
goto error_configure;
}

pRequest->m_State = EHttpState::RUNNING;
m_RunningRequests.emplace(pEH, std::move(pRequest));
NewRequests.pop_front();
continue;
Expand Down
2 changes: 2 additions & 0 deletions src/engine/shared/http.h
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ class CHttpRequest : public IHttpRequest
char m_aErr[256]; // 256 == CURL_ERROR_SIZE
std::atomic<EHttpState> m_State{EHttpState::QUEUED};
std::atomic<bool> m_Abort{false};
std::mutex m_WaitMutex;
std::condition_variable m_WaitCondition;

int m_StatusCode = 0;
bool m_HeadersEnded = false;
Expand Down

0 comments on commit a397688

Please sign in to comment.