If boost::threads represent the C of multithreaded programming, then RAII and automatically managed threads represent the C++ of multithreaded programming.
In the last article we promised that using more RAII would allow us to get this code even smaller and better to manage. Here is the result of that:
class threaded_class { public: threaded_class() : m_stoprequested(false), m_thread(boost::bind(&threaded_class::do_work, this)) //Note 2 { } ~threaded_class() { m_stoprequested = true; m_thread.join(); //Note 2 } int get_fibonacci_value(int which) { boost::mutex::scoped_lock l(m_mutex); return m_fibonacci_values.get(which); } private: volatile bool m_stoprequested; std::vector<int> m_fibonacci_values; boost::mutex m_mutex; boost::thread m_thread; int fibonacci_number(int num) { switch(num) { case 0: case 1: return 1; default: return fib(num-2) + fib(num-1); }; } // Compute and save fibonacci numbers as fast as possible void do_work() { int iteration = 0; while (!m_stoprequested) { int value = fibonacci_number(iteration); boost::mutex::scoped_lock l(m_mutex); m_fibonacci_values.push_back(value); } } };
By using RAII techniques we were able to cut our last example of boost::threads down from 64 lines of code to 52; a 20% savings in code size. Overall we are down by 35% from the original pthreads version.
Notes regarding this version:
m_thread object is the last object created. We ensure this by declaring it last. Why is this critical? The thread needs to use other objects in the class. By creating it last we make sure that all dependent objects are already created and ready to go by the time the thread is running.In proper RAII fashion this class creates and manages all of its own resources, including its thread.
In the next article we will look at making this method of RAII managed threads generic so that we can reuse this technique.
Recent comments
9 hours 24 min ago
14 hours 28 min ago
14 hours 57 min ago
1 day 7 hours ago
1 day 14 hours ago
1 week 6 days ago
3 weeks 8 hours ago
3 weeks 1 day ago
3 weeks 3 days ago
3 weeks 4 days ago