4 ms·
So, how would you write that line?
by sam_goody 2y ago
So, how would you write that line?
- Jtsummers 2y agoThrow in a mutex and a condition variable. Many languages and systems (including C++) with locks allow you to set a timeout (either a specific time to wake or a delay and then wake). Use a notify in the write thread to wake the reader. https://en.cppreference.com/w/cpp/thread/condition_variable https://en.cppreference.com/w/cpp/thread/condition_variable - C++11 so not available in this form to the blog writer, but an equivalent was. EDIT: I had C++ on the brain, the code is in Java and they're already using notifyAll. The wait should just be to the timeout limit and not shorter. If the data is ready in under a second, the notifyAll will wake the thread and it can keep running and there's no risk of waiting an extra second (approx) past the actual deadline as the current code would do.
- IshKebab 2y agoHonestly the fact that a thread is even waiting for a map value to be filled in is a bit of a red flag. 99% of multithreaded code should be using channels or parallel for/map. If you have to have a thread wait for a value from another then use a condition variable like he said. https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/Condition.html https://docs.oracle.com/javase/8/docs/api/java/util/concurre...
- deleted 2y ago[deleted]
- mystified5016 2y ago99.999% of the time if you've hardcoded a delay, you should have done anything else. The correct tool here is cross-thread synchronization. You can do this in many ways, but for a simple situation like this, I'd use a mutex or a semaphore or something. In my opinion as an embedded programmer, the only time it's appropriate to hardcode a delay this way is if you're actually waiting on a physical process to happen. For instance, when I bring up a power rail in my widget, I have a delay of a few hundred milliseconds for capacitors to charge, power to stabilize, and chips to boot. Waiting five seconds for another thread to push data is not appropriate. We have entire ecosystems of tools to communicate between threads. Sleeping a thread is not one of those, and you typically only see that if the author doesn't understand the tools properly. It's a very beginner mistake.