00001 // @file queue.h 00002 00003 /* Copyright 2009 10gen Inc. 00004 * 00005 * Licensed under the Apache License, Version 2.0 (the "License"); 00006 * you may not use this file except in compliance with the License. 00007 * You may obtain a copy of the License at 00008 * 00009 * http://www.apache.org/licenses/LICENSE-2.0 00010 * 00011 * Unless required by applicable law or agreed to in writing, software 00012 * distributed under the License is distributed on an "AS IS" BASIS, 00013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00014 * See the License for the specific language governing permissions and 00015 * limitations under the License. 00016 */ 00017 00018 #pragma once 00019 00020 #include "../pch.h" 00021 00022 #include <queue> 00023 00024 #include "../util/timer.h" 00025 00026 namespace mongo { 00027 00031 template<typename T> class BlockingQueue : boost::noncopyable { 00032 public: 00033 BlockingQueue() : _lock("BlockingQueue") { } 00034 00035 void push(T const& t) { 00036 scoped_lock l( _lock ); 00037 _queue.push( t ); 00038 _condition.notify_one(); 00039 } 00040 00041 bool empty() const { 00042 scoped_lock l( _lock ); 00043 return _queue.empty(); 00044 } 00045 00046 bool tryPop( T & t ) { 00047 scoped_lock l( _lock ); 00048 if ( _queue.empty() ) 00049 return false; 00050 00051 t = _queue.front(); 00052 _queue.pop(); 00053 00054 return true; 00055 } 00056 00057 T blockingPop() { 00058 00059 scoped_lock l( _lock ); 00060 while( _queue.empty() ) 00061 _condition.wait( l.boost() ); 00062 00063 T t = _queue.front(); 00064 _queue.pop(); 00065 return t; 00066 } 00067 00068 00074 bool blockingPop( T& t , int maxSecondsToWait ) { 00075 00076 Timer timer; 00077 00078 boost::xtime xt; 00079 boost::xtime_get(&xt, boost::TIME_UTC); 00080 xt.sec += maxSecondsToWait; 00081 00082 scoped_lock l( _lock ); 00083 while( _queue.empty() ) { 00084 if ( ! _condition.timed_wait( l.boost() , xt ) ) 00085 return false; 00086 } 00087 00088 t = _queue.front(); 00089 _queue.pop(); 00090 return true; 00091 } 00092 00093 private: 00094 std::queue<T> _queue; 00095 00096 mutable mongo::mutex _lock; 00097 boost::condition _condition; 00098 }; 00099 00100 }