-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
79 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
#ifndef _TASK_QUEUE_H_ | ||
#define _TASK_QUEUE_H_ | ||
#define __STDC_LIMIT_MACROS | ||
|
||
#include <mutex> | ||
#include <deque> | ||
#include "common.h" | ||
|
||
namespace TwoPaCo | ||
{ | ||
class TaskQueue | ||
{ | ||
public: | ||
TaskQueue() | ||
{ | ||
|
||
} | ||
|
||
bool try_push(const Task & task) | ||
{ | ||
bool ret = false; | ||
mutex_.lock(); | ||
|
||
if (queue_.size() < capacity_) | ||
{ | ||
queue_.push_back(task); | ||
ret = true; | ||
} | ||
|
||
mutex_.unlock(); | ||
return ret; | ||
} | ||
|
||
bool try_pop(Task& task) | ||
{ | ||
bool ret = false; | ||
mutex_.lock(); | ||
if (queue_.size() > 0) | ||
{ | ||
task = queue_.front(); | ||
queue_.pop_front(); | ||
ret = true; | ||
} | ||
|
||
mutex_.unlock(); | ||
return ret; | ||
} | ||
|
||
void set_capacity(size_t capacity) | ||
{ | ||
mutex_.lock(); | ||
capacity_ = capacity; | ||
mutex_.unlock(); | ||
} | ||
|
||
size_t size() | ||
{ | ||
mutex_.lock(); | ||
size_t ret = queue_.size(); | ||
mutex_.unlock(); | ||
return ret; | ||
} | ||
|
||
size_t capacity() const | ||
{ | ||
return capacity_; | ||
} | ||
|
||
private: | ||
size_t capacity_; | ||
std::mutex mutex_; | ||
std::deque<Task> queue_; | ||
DISALLOW_COPY_AND_ASSIGN(TaskQueue); | ||
}; | ||
|
||
typedef std::unique_ptr<TaskQueue> TaskQueuePtr; | ||
} | ||
|
||
#endif |