c++ - Passing data from caller thread to the method in another boost::thread -
i have rather noob question regarding concurrency in c++ (using boost threads) on haven't found clear answer.i have worker class runs in separate thread.i init worker on start of program once.this worker "lazy" , data encoding when receives calling thread.in worker have public method:
void pushframe(byte* data);
which pushes data std::stack member variable worker can access each time new data object pushed there.
what don't understand how such interaction done? can call pushframe() caller thread , pass argument? or have access methods in worker in special way?
usually use producer-consumer-queue type of work.
whenever worker thread runs out of work wait()
s on boost::condition_variable
protected same boost::mutex
stack holding data worker thread (you might want use queue here instead minimize risk of unfair work scheduling).
your pushframe()
function calls notify_one()
on condition variable whenever inserts new data stack. way, worker thread sleep (i.e. os scheduler not give timeslice) until there work done.
the easiest thing wrong here locking of mutex protecting both stack , condition_variable. besides avoiding races on data structures, need take care condition_variable not miss notify call , therefore might stuck waiting while there more work available.
class worker { void pushframe(byte* data) { boost::lock_guard<boost::mutex> lk(m_mutex); // push data // ... m_data_cond.notify_one(); } void dowork() { while(!done) { boost::unique_lock<boost::mutex> lk(m_mutex); // need loop here wait() may return spuriously while(is_out_of_work()) { // wait() release mutex , suspend thread m_data_cond.wait(lk); // upon returning wait() mutex locked again } // work queue // ... } } boost::mutex m_mutex; boost::condition_variable m_data_cond; [...] };
Comments
Post a Comment