c++ - thread-safe, data-race free, lag-free shared container (circular_buffer) -


i face following situation (which have admit i'm noob trust myself in solving alone..): have thread creates new cv::mat objects thread b consume. need thread-safe container c (a boost::circular_buffer in case) hold cv::mat objects thread generates. then, thread b needs iterate through items in c produce animation. therefore need thread-safe c disallow data-races cause no (ideally) or small (if not possible otherwise) lag thread b's animation -> dot want thread b freeze when thread updates c. best come this:

#include <boost/circular_buffer.hpp> #include <opencv2/core.hpp> #include <boost/core/noncopyable.hpp> #include <memory> #include <type_traits> #include <algorithm>  using im_buf = boost::circular_buffer<cv::mat>; class imagebuffer : private boost::noncopyable {  private:   im_buf buffer;   std::mutex mtx;   std::unique_lock<std::mutex> lock; public:   // operator<< accepting cv::mat, cv::mat& , cv::mat&&   template <class t,     class = typename std::enable_if     <std::is_same<cv::mat, typename std::decay<t>::type>      ::value>::type>    void operator<<(t&& mat) {       lock.lock();       buffer.push_back(std::forward<t>(mat));       lock.unlock();     }     template <typename func> // excpect callable objects     inline void iterate(func func) {       lock.lock();       std::for_each(buffer.begin(),buffer.end(),func);       lock.unlock();     }     inline imagebuffer():       buffer {settings::max_images_in_loop},       mtx {},       lock {mtx} {}     ~imagebuffer()=default;     imagebuffer(const imagebuffer&&)=delete;      imagebuffer& operator=(const imagebuffer&&)=delete;   }; 

(note if not invariant, thread b not suppose mutate c or of contents (i'd love use const_iterator here boost::circular_buffer not provide one..)

yet, code thread b freeze entire animation time each time thread adds new elements.. so, a. isn't there better approach?? b. implementation thread safe?

if problem animation, worrying wrong thing. mutexes fine purpose - don't worry stalling.

ideally need produce frames @ 60fps. may away little 20fps depending on application. until advent of digital cinema, cinemas showed 24fps.

60fps means have 16 milliseconds render frame. on 1ghz processor that's 16 million clock cycles. avoid stuttering due other processes, need use less half of that, 4-8 million cycles, 50% 75% of processor time idle, , use 4-8 milliseconds of processor time rendering frame.

waiting other threads, mutexes or other resources affects animation if causes miss deadline next frame.

if thread has wait once every few frames, few tens of thousand clock cycles due mutex, not affect rendering because still have plenty of time before next frame due shown on screen.


Comments