Files
mongo/util/queue.h

101 lines
2.4 KiB
C
Raw Normal View History

2010-06-01 08:56:06 -04:00
// @file queue.h
2009-04-17 17:07:04 -04:00
/* Copyright 2009 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
2009-04-17 17:07:04 -04:00
#pragma once
2010-04-27 15:27:52 -04:00
#include "../pch.h"
2009-04-17 17:07:04 -04:00
#include <queue>
#include "../util/timer.h"
2009-04-17 17:07:04 -04:00
namespace mongo {
2011-01-04 00:40:41 -05:00
2009-04-17 17:07:04 -04:00
/**
* simple blocking queue
*/
template<typename T> class BlockingQueue : boost::noncopyable {
public:
2010-05-26 00:46:49 -04:00
BlockingQueue() : _lock("BlockingQueue") { }
2011-01-04 00:40:41 -05:00
void push(T const& t) {
scoped_lock l( _lock );
2009-04-17 17:07:04 -04:00
_queue.push( t );
_condition.notify_one();
}
2011-01-04 00:40:41 -05:00
2009-04-17 17:07:04 -04:00
bool empty() const {
scoped_lock l( _lock );
2009-04-17 17:07:04 -04:00
return _queue.empty();
}
2011-01-04 00:40:41 -05:00
bool tryPop( T & t ) {
scoped_lock l( _lock );
2009-04-17 17:07:04 -04:00
if ( _queue.empty() )
return false;
2011-01-04 00:40:41 -05:00
2009-04-17 17:07:04 -04:00
t = _queue.front();
_queue.pop();
2011-01-04 00:40:41 -05:00
2009-04-17 17:07:04 -04:00
return true;
}
2011-01-04 00:40:41 -05:00
T blockingPop() {
2009-04-17 17:07:04 -04:00
scoped_lock l( _lock );
2009-04-17 17:07:04 -04:00
while( _queue.empty() )
_condition.wait( l.boost() );
2011-01-04 00:40:41 -05:00
2009-04-17 17:07:04 -04:00
T t = _queue.front();
_queue.pop();
2011-01-04 00:40:41 -05:00
return t;
2009-04-17 17:07:04 -04:00
}
2011-01-04 00:40:41 -05:00
/**
* blocks waiting for an object until maxSecondsToWait passes
* if got one, return true and set in t
* otherwise return false and t won't be changed
*/
2011-01-04 00:40:41 -05:00
bool blockingPop( T& t , int maxSecondsToWait ) {
Timer timer;
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += maxSecondsToWait;
scoped_lock l( _lock );
2011-01-04 00:40:41 -05:00
while( _queue.empty() ) {
2010-09-20 13:15:24 -04:00
if ( ! _condition.timed_wait( l.boost() , xt ) )
return false;
}
2011-01-04 00:40:41 -05:00
t = _queue.front();
_queue.pop();
return true;
}
2011-01-04 00:40:41 -05:00
2009-04-17 17:07:04 -04:00
private:
std::queue<T> _queue;
2011-01-04 00:40:41 -05:00
mutable mongo::mutex _lock;
2009-04-17 17:41:07 -04:00
boost::condition _condition;
2009-04-17 17:07:04 -04:00
};
}