Merge branch 'upstream' into dfsg-orig
[debian/gnuradio] / gruel / src / lib / msg / msg_queue.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2009 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
18  * along with GNU Radio; see the file COPYING.  If not, write to
19  * the Free Software Foundation, Inc., 51 Franklin Street,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include <gruel/msg_queue.h>
28 #include <stdexcept>
29
30 using namespace pmt;
31
32 namespace gruel {
33
34   msg_queue_sptr
35   make_msg_queue(unsigned int limit)
36   {
37     return msg_queue_sptr(new msg_queue(limit));
38   }
39   
40   msg_queue::msg_queue(unsigned int limit)
41     : d_limit(limit)
42   {
43   }
44   
45   msg_queue::~msg_queue()
46   {
47     flush();
48   }
49
50   void
51   msg_queue::insert_tail(pmt_t msg)
52   {
53     gruel::scoped_lock guard(d_mutex);
54
55     while (full_p())
56       d_not_full.wait(guard);
57
58     d_msgs.push_back(msg);
59     d_not_empty.notify_one();
60   }
61
62   pmt_t
63   msg_queue::delete_head()
64   {
65     gruel::scoped_lock guard(d_mutex);
66
67     while (empty_p())
68       d_not_empty.wait(guard);
69
70     pmt_t m(d_msgs.front());
71     d_msgs.pop_front();
72
73     if (d_limit > 0)            // Unlimited length queues never block on write
74       d_not_full.notify_one();
75
76     return m;
77   }
78
79   pmt_t
80   msg_queue::delete_head_nowait()
81   {
82     gruel::scoped_lock guard(d_mutex);
83
84     if (empty_p())
85       return pmt_t();
86         
87     pmt_t m(d_msgs.front());
88     d_msgs.pop_front();
89
90     if (d_limit > 0)            // Unlimited length queues never block on write
91       d_not_full.notify_one();
92
93     return m;
94   }
95
96   void
97   msg_queue::flush()
98   {
99     while (delete_head_nowait() != pmt_t())
100       ;
101   }
102
103 } /* namespace gruel */