|
Boost Users : |
From: Xiaofan Li (mr.xiaofan.li_at_[hidden])
Date: 2007-12-28 08:51:15
Hi,
Sorry to disturb the list but I've been stuck with this problem for a while. The
idea is to pass the reference of some data object to the thread function, in
which the data object (by which the ref is passed in) will be modified. However
I have found that this would not work at run-time, as the program compiled, ran
but the modifying code silently failed to execute.
I've written a small sample, which is self-contained and compilable:
//
// File: thread_test.cc
// Author: xli
//
// Created on December 26, 2007, 12:26 AM
//
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <vector>
using namespace std;
int s_count = 0;
boost::mutex mutex;
struct some_data_t
{
some_data_t() : m_int(0) {}
int m_int;
vector<int> m_vec;
};
class threaded
{
public:
void increment_count( some_data_t& data )
{
boost::mutex::scoped_lock lock(mutex);
std::cout << "count = " << ++s_count << std::endl;
data.m_int += s_count;
data.m_vec.push_back(s_count);
}
};
some_data_t a;
int main(int argc, char* argv[])
{
threaded _thrd;
boost::thread_group threads;
for (int i = 0; i < 10; ++i)
threads.create_thread( boost::bind( boost::mem_fn(
&threaded::increment_count ), &_thrd, a ) );
threads.join_all();
cout <<"All done. " <<a.m_int <<" " <<a.m_vec.size() <<endl;
}
-----------------
The output (g++4.3/linux) is
count = 1
count = 2
...
count = 10
All done. 0 0
However I am expecting the last line as "All done. 55 10" as indicated in
increment_count(). I have no idea why the "some_data_t a" did not undergo any
change even increment_count() had clearly been called 10 times.
I also wish to note that the way I make a member func version of
increment_count() is purely for testing and changing it back to a global/static
function will not alter the un-designated behaviour I've got.
Any opinions on this are more than welcome.
Regards,
Xiaofan
-- Xiaofan Li
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net