condition-variable

C++11 thread-safe queue

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-26 05:17:02
问题 A project I\'m working on uses multiple threads to do work on a collection of files. Each thread can add files to the list of files to be processed, so I put together (what I thought was) a thread-safe queue. Relevant portions follow: // qMutex is a std::mutex intended to guard the queue // populatedNotifier is a std::condition_variable intended to // notify waiting threads of a new item in the queue void FileQueue::enqueue(std::string&& filename) { std::lock_guard<std::mutex> lock(qMutex); q

Why do pthreads’ condition variable functions require a mutex?

会有一股神秘感。 提交于 2019-11-26 01:43:50
问题 I’m reading up on pthread.h ; the condition variable related functions (like pthread_cond_wait(3) ) require a mutex as an argument. Why? As far as I can tell, I’m going to be creating a mutex just to use as that argument? What is that mutex supposed to do? 回答1: It's just the way that condition variables are (or were originally) implemented. The mutex is used to protect the condition variable itself . That's why you need it locked before you do a wait. The wait will "atomically" unlock the