Imported Upstream version 3.2.2
[debian/gnuradio] / gnuradio-core / src / lib / runtime / gr_sptr_magic.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2008 Free Software Foundation, Inc.
4  * 
5  * This file is part of GNU Radio
6  * 
7  * GNU Radio is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3, or (at your option)
10  * any later version.
11  * 
12  * GNU Radio is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24 #include <gr_sptr_magic.h>
25 #include <gr_hier_block2.h>
26 #include <map>
27 #include <stdexcept>
28
29
30 #if 0
31   #include <boost/thread.hpp>
32   typedef boost::mutex                  mutex;
33   typedef boost::mutex::scoped_lock     scoped_lock;
34 #else
35   #include <gnuradio/omnithread.h>
36   typedef omni_mutex                    mutex;
37   typedef omni_mutex_lock               scoped_lock;
38 #endif
39
40 namespace gnuradio {
41
42   static mutex          s_mutex;
43   typedef std::map<gr_basic_block*, gr_basic_block_sptr> sptr_map;
44   static sptr_map       s_map;
45
46   void
47   detail::sptr_magic::create_and_stash_initial_sptr(gr_hier_block2 *p)
48   {
49     gr_basic_block_sptr sptr(p);
50     scoped_lock l();
51     s_map.insert(sptr_map::value_type(static_cast<gr_basic_block *>(p), sptr));
52   }
53
54
55   gr_basic_block_sptr 
56   detail::sptr_magic::fetch_initial_sptr(gr_basic_block *p)
57   {
58     /*
59      * If p isn't a subclass of gr_hier_block2, just create the
60      * shared ptr and return it.
61      */
62     gr_hier_block2 *hb2 = dynamic_cast<gr_hier_block2 *>(p);
63     if (!hb2){
64       return gr_basic_block_sptr(p);
65     }
66
67     /*
68      * p is a subclass of gr_hier_block2, thus we've already created the shared pointer
69      * and stashed it away.  Fish it out and return it.
70      */
71     scoped_lock l();
72     sptr_map::iterator pos = s_map.find(static_cast<gr_basic_block *>(p));
73     if (pos == s_map.end())
74       throw std::invalid_argument("gr_sptr_magic: invalid pointer!");
75
76     gr_basic_block_sptr sptr = pos->second;
77     s_map.erase(pos);
78     return sptr;
79   }
80 };
81