Reply to comment

Auto-stopping Threads

I would put to use RAII management of my thread: (this is covered in Multithreaded C++: Part 3: RAII And Threads)

I would update the destructor of this class to automatically shutdown the thread when it is called:

 ~threaded_class()
    {
      //Warning this stop call will fail if stop had been called previously, 
      //see Multithreaded C++: Part 3: RAII And Threads for a more robust
      //example
      stop(); 
    }

Then I would place the object at the appropriate scope so that its lifetime was what I needed it to be.

int main()
{
  threaded_class fibcalc;
 
  //Do stuff
  doSomethingWithFibCalc(fibcalc);
 
  //When main() exits fibcalc is popped from the stack, its destructor is called and the
  //Thread is automatically stopped and joined.
}

I feel compelled to point out that this example is mostly academic. It's a fun way to illustrate the use of boost threads and mutexes, but it's a very inefficient way of calculating the Fibonacci sequence. A method utilising a cache or even calculating the sequence statically at compile time is a much better option.

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • Lines and paragraphs break automatically.
  • You may post PHP code. You should include <?php ?> tags.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <cpp>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
5 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.