Pages

Functor and boost::thread

We have just seen how to create a boost::thread object associated to a free function, so to run it in a different thread.

I have already written a post on using functor instead. In that case I was working on Windows and VC++, but the code didn't need to be changed at all to run on Linux and g++.

Actually, after testing that no change was required, I did change it a bit, to comply with a slightly different code-style and, to introduce some thrill, adding a short sleep after any write.

Here is the new version:

#include <iostream>
#include <boost/thread.hpp>

namespace
{
class Count
{
static boost::mutex mio_;
const int multi_;
public:
Count(const int multi) : multi_(multi) { }

void operator()()
{
for(int i = 0; i < 10; ++i)
{
{
boost::lock_guard<boost::mutex> lock(mio_);
std::cout << "Thread " << boost::this_thread::get_id()
<< " is looping: " << i*multi_ << std::endl;
}
boost::this_thread::sleep(boost::posix_time::millisec(50));
}
}
};

boost::mutex Count::mio_;
}

void mt02()
{
std::cout << "Main thread " << boost::this_thread::get_id() << std::endl;
boost::thread t1(Count(1));
boost::thread t2(Count(-1));
t1.join();
t2.join();
std::cout << "Back to the main thread " << std::endl;
}

As already said in the original post, there is no real need for a functor for such a limited functionality, when a function could do fine. The only nuisance was on the parameter binding, but since a call to bind is done in the boost::thread constructor when required, there is no reason to prefer a functor in such a simple case.

Here is the new version of the code - also in this case the slight changes were not due to the change of the development platform:

#include <iostream>
#include <boost/thread.hpp>

using namespace std;

namespace
{
boost::mutex mio;

void counter(const int multi)
{
for(int i = 0; i < 10; ++i)
{
boost::this_thread::sleep(boost::posix_time::millisec(20)); // 1.
{
boost::lock_guard<boost::mutex> lock(mio);
cout << boost::this_thread::get_id() << ": " << multi * i << endl;
}
}
}
}

void mt03()
{
// boost::thread t1(boost::bind(&myCount, 1));
// boost::thread t2(boost::bind(&myCount, -1)); // 2.
boost::thread t1(&counter, 1);
boost::thread t2(&counter, -1);

t1.join();
t2.join();
}

1. Just to change things a bit, here the sleep is before writing.
2. We could have written the binding explicitly, but it is not required.

No comments:

Post a Comment