Shared memory/mutex/parallel_for

Shared memory/mutex/parallel_for

Hi all,

I have a question that might seem trivial to experience multi-threading programmers... I want to do something similar than this "trivial" example, where a memory is shared between threads:

#include ....

typedef tbb::spin_mutex CopyToSharedMemoryMutex;
CopyToSharedMemoryMutex myMutex;

struct Summer
Summer(const std::vector &vect,
int &sum)
: m_vect(vect),

operator()(const tbb::blocked_range &r) const {
for (size_t i = r.begin(); i != r.end(); ++i) {
CopyToSharedMemoryMutex lock(myMutex);
m_sum += m_vect[i];


const std::vector m_vect;
int &m_sum;

main(int argc, char *argv[])

int sum = 0;
const size_t SIZE = 100000000;
std::vector vect(SIZE, 1);
Summer summer(vect, sum);
tbb::parallel_for(tbb::blocked_range(0, vect.size()), summer);
std::cout << sum << std::endl;

std::vector::const_iterator it = vect.begin();
const std::vector::const_iterator itEnd = vect.end();
for (; it != itEnd; ++it) {
sum += *it;
std::cout << sum << std::endl;

As you can see, a reference to int sum is passed to the Body object Summer. At first I expected the parallel version not to give the right answer since sum is shared and might not always be correctly incremented. That's why I added the spin_mutex, but the problem remained the same, which I dont understand. Any help, link to appropriate documentation or other forum thread would be appreciated.


PS: system info, Linux Fedora Core 15, with gcc version 4.6.1

3 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.
Best Reply

You made a copy of the mutex instead of locking it. Instead, do "CopyToSharedMemoryMutex::scoped_lock lock(myMutex);".

I've proposed to make all mutexes noncopyable (which would have alerted you to the problem), as they are in C++11.

That was indeed the solution! Thank you Raf


Leave a Comment

Please sign in to add a comment. Not a member? Join today