CodeSOD: Sleep on It

This post was originally published on this site

The Daily WTF

If you’re fetching data from a remote source, “retry until a timeout is hit” is a pretty standard pattern. And with that in mind, this C++ code from Auburus doesn’t look like much of a WTF.

bool receiveData(uint8_t** data, std::chrono::milliseconds timeToWait) { start = now(); while ((now() – start) < timeToWait) { if (/* successfully receive data */) { return true; } std::this_thread::sleep_for(100ms); } return false; }

Track the start time. While the difference between the current time and the start is less than our timeout, try and get the data. If you don’t, sleep for 100ms, then retry.

This all seems pretty reasonable, at first glance. We could come up with better ways, certainly, but that code isn’t quite a WTF.

This code is:

// The ONLY call to that function receiveData(&dataPtr, 100ms);

By calling this with a 100ms timeout, and because we hard-coded

To read the full article click on the 'post' link at the top.