c++ - Using boost::mutex as a private member of class -
i have class contains boost::mutex private member. becomes locked when call 1 of public functions , unlocks when function exits. provide synchronous access object's internals.
class stringdeque { boost::mutex mtx; std::deque<string> string_deque; public: stringdeque() { } void addtodeque(const string& str_to_add) { boost::lock_guard<boost::mutex> guard(mtx); string_deque.push(str_to_add); } string popfromdeque() { boost::lock_guard<boost::mutex> guard(mtx); string popped_string = string_deque.front(); string_deque.pop(); return popped_string; } };
this class isn't meant particularly useful playing around mutexes , threads.
i have main() has function defined pops strings class , prints them in thread. repeat 10 times , return function. once again, purely testing purposes. looks this:
void printthestrings(stringdeque& str_deque) { int = 0; while(i < 10) { string popped_string = str_deque.popfromdeque(); if(popped_string.empty()) { sleep(1); continue; } cout << popped_string << endl; ++i; } } int main() { stringdeque str_deque; boost::thread the_thread(printthestrings, str_deque); str_deque.addtodeque("say prayers"); str_deque.addtodeque("little one"); str_deque.addtodeque("and don't forget son"); str_deque.addtodeque("to include everyone"); str_deque.addtodeque("i tuck in"); str_deque.addtodeque("warm within"); str_deque.addtodeque("keep free sin"); str_deque.addtodeque("until sandman comes"); str_deque.addtodeque("sleep 1 eye open"); str_deque.addtodeque("gripping pillow tight"); the_thread.join(); }
the error keep getting boost::mutex noncopyable. printthestrings() function takes reference little confused why trying copy object.
i have read bit on , 1 solution keep reading make boost::mutex static private member of object. however, defeats purpose of mutex since want on object-by-object basis rather class variable.
is bad use of mutexes? should rethinking entire application?
edit:
i discovered condition_variable should serve purpose lot better have thread wait until there in deque before waking pop deque , print it. examples see define these mutexes , condition_variable objects @ global scope. seems very... not object-oriented in opinion. examples straight boost show done in way. how other people use these objects?
you correct printtostring
takes stringqueue
reference. problem boost::thread
take arguments value. force take arguments reference need modify things to:
boost::thread the_thread(printthestrings, boost::ref(str_deque));
as aside, c++11 onwards, threads part of standard library. should use std::thread instead
Comments
Post a Comment