Community
cancel
Showing results for 
Search instead for 
Did you mean: 
remi_vieux
Beginner
71 Views

Shared memory/mutex/parallel_for

Jump to solution
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:

//main.cpp
#include ....

typedef tbb::spin_mutex CopyToSharedMemoryMutex;
CopyToSharedMemoryMutex myMutex;

struct Summer
{
Summer(const std::vector &vect,
int ∑)
: m_vect(vect),
m_sum(sum)
{}

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

}

const std::vector m_vect;
int &m_sum;
};

int
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;

sum=0;
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;
return EXIT_SUCCESS;
}


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.

Thanks,
Remi

PS: system info, Linux Fedora Core 15, with gcc version 4.6.1
0 Kudos
1 Solution
RafSchietekat
Black Belt
71 Views
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.

View solution in original post

2 Replies
RafSchietekat
Black Belt
72 Views
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.

View solution in original post

remi_vieux
Beginner
71 Views
That was indeed the solution! Thank you Raf

Regards
Reply