I'd like to have a function that multiple threads can call, passing an int each. The function will calculate a sum of the ints by using a lock, and then return the sum to each of the threads. I still haven't ironed out my understanding of function argument and return behavior, with multiple threads. Anyway, here's a running of a test program:
Code:
$ ./main
How many threads? 5
0 in called f.
1 in called f.
2 in called f.
3 in called f.
4 in called f.
0
0
0
0
0
$
Code:
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/thread/barrier.hpp>
#include <boost/thread/mutex.hpp>
#include <vector>
boost::mutex moo;
int sum;
int f(int in, boost::barrier & bar)
{
{
boost::mutex::scoped_lock lk(moo);
std::cout << in << " in called f." << std::endl;
sum += in;
}
bar.wait();
return sum;
}
struct task
{
boost::barrier & bar;
int total;
int n;
task(int n_, boost::barrier & bar_) : n(n_), bar(bar_) {}
void operator()() { total = f(n,bar); }
};
int main()
{
std::cout << "How many threads? ";
unsigned int n;
std::cin >> n;
boost::barrier bar(n);
std::vector<task*> tasks;
boost::thread_group tg;
sum = 0;
for(unsigned int i = 0; i < n; ++i)
{
tasks.push_back( new task(i,bar) );
tg.create_thread( *(tasks.back()) );
}
tg.join_all();
for(unsigned int i = 0; i < tasks.size(); ++i)
{
std::cout << tasks[i]->total << std::endl;
delete tasks[i];
}
}
Regardless of what a task passes to f, total is always zero. Even having f return a constant yields the same behavior. Is the act of returning causing a problem?