de0bed029d890df5341a5d16a12956696843ba82
[dcpomatic.git] / src / lib / exception_store.h
1 /*
2     Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifndef DCPOMATIC_EXCEPTION_STORE_H
21 #define DCPOMATIC_EXCEPTION_STORE_H
22
23 #include <boost/exception/all.hpp>
24 #include <boost/thread/mutex.hpp>
25
26 /** @class ExceptionStore
27  *  @brief A parent class for classes which have a need to catch and
28  *  re-throw exceptions.
29  *
30  *  This is intended for classes which run their own thread; they should do
31  *  something like
32  *
33  *  void my_thread ()
34  *  try {
35  *    // do things which might throw exceptions
36  *  } catch (...) {
37  *    store_current ();
38  *  }
39  *
40  *  and then in another thread call rethrow().  If any
41  *  exception was thrown by my_thread it will be stored by
42  *  store_current() and then rethrow() will re-throw it where
43  *  it can be handled.
44  */
45 class ExceptionStore
46 {
47 public:
48         void rethrow () {
49                 boost::mutex::scoped_lock lm (_exception_mutex);
50                 if (_exception) {
51                         boost::exception_ptr tmp = _exception;
52                         _exception = boost::exception_ptr ();
53                         boost::rethrow_exception (tmp);
54                 }
55         }
56
57 protected:
58
59         void store_current () {
60                 boost::mutex::scoped_lock lm (_exception_mutex);
61                 _exception = boost::current_exception ();
62         }
63
64 private:
65         boost::exception_ptr _exception;
66         mutable boost::mutex _exception_mutex;
67 };
68
69 #endif