c++ - Difference between Boost and Pthread condition variables -
i found code using boost threads, mutexes , condition variables wanna try rewrite code posix threads.
this boost code, i´ve found here:
void push(data const& data) { boost::mutex::scoped_lock lock(the_mutex); the_queue.push(data); lock.unlock(); the_condition_variable.notify_one(); } in code using pthreads not sure if i´m using condition variables right way because not sure if notify_one() , singalling variables same:
void push(t const& data) { pthread_mutex_lock(&m_mutex); m_queue.push(data); pthread_mutex_unlock(&m_mutex); pthread_cond_signal(&m_condition); } initializing done right before that:
pthread_mutex_t m_mutex = pthread_mutex_initializer; pthread_cond_t m_condition = pthread_cond_initializer; at point using the_condition_variable.wait(lock); ... line rewrite pthreads that: pthread_cond_wait( &m_condition, &m_mutex);
am on right track?
the semantics of boost threading primitives based on pthread, there should no difference @ level. boost wraps them in c++ class based interface, however, , in particular, supports raii implicitly things locking mutex; if want use pthread directly, you'll want implement own variant of scoped lock, example. stands, implementation of push fails release lock if m_queue.push( data ) throws (and can throw).
also, should signal before releasing lock. (this error both in boost code , in pthread code.) , avoid code in site cite: broken, , not @ thread safe.
edit:
after more investigation: see site quote authored anthony williams, has very high reputation regards threading issues. @ bottom of page, has "the final code" version is correct, in every detail. although doesn't seem clear me, on reading page, think of preceding versions (including 1 you're copying from) given "first drafts", , known incorrect in details. (i still think should make clearer. there extremely dangerous practices in first example: returning references, example.)
Comments
Post a Comment