To protect the vector, you need boost :: mutex, and you can use boost :: mutex :: scoped_lock, which will lock the mutex in its constructor and unlock it in the destructor
Keep in mind that you need to use the same mutex wherever you access this vec instance, whether read or write.
For you to go, you could do something like:
struct Worker { boost::mutex &vec_mutex; Worker(std::vector<double>* v,boost::mutex &v_mutex) : vec(v),vec_mutex(v_mutex) {} void operator() { // do some long computation and then add results to *vec, eg boost::mutex::scoped_lock lock(vec_mutex); for(std::size_t i = 0; i < vec->size(); ++i) { (*vec)[i] += some_value; } } };
For more advanced materials, you have to encapsulate the vector and the mutex further, or sooner or later you forget that they must be connected, and you will have access to vec somewhere without holding the lock, which is very difficult to debug problems. For problems like this example, I would prefer that the workers use their own separate vectors and combine the result in the control flow when the workers are done.
source share