Skip to content

Commit

Permalink
add GlobalQueue implement
Browse files Browse the repository at this point in the history
  • Loading branch information
fs committed Mar 7, 2024
1 parent 8b175c6 commit 41f4e74
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
41 changes: 40 additions & 1 deletion c++/async_task/src/task_queue.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,49 @@ std::shared_ptr<Task> TaskQueue::try_deque() {
if (_queue.empty()) {
return nullptr;
}

auto task = _queue.front();
_queue.pop();
return task;
}

const std::shared_ptr<TaskQueue>& GlobalQueue::get_main_queue() {
static std::shared_ptr<TaskQueue> g_main_queue = std::make_shared<TaskQueue>("main_queue");
return g_main_queue;
}

std::shared_ptr<TaskQueue> GlobalQueue::get_queue_by_name(const std::string &queue_name){
auto it = _queue_map.find(queue_name);
if (it != _queue_map.end()) {
return it->second;
} else {
return nullptr;
}
}


// 获取默认的全局后台队列
std::shared_ptr<TaskQueue> GlobalQueue::get_background_queue() {
static std::shared_ptr<TaskQueue> background_queue = std::make_shared<TaskQueue>("background");
return background_queue;
}

void GlobalQueue::init_queues(const std::vector<std::string>& queue_names) {
get_main_queue();
get_background_queue();
for (auto& name : queue_names) {
init_queue(name);
}
}

bool GlobalQueue::init_queue(const std::string& queue_name) {
if(get_queue_by_name(queue_name) != nullptr) {
return false;
}
auto queue = std::make_shared<TaskQueue>(queue_name);
_queue_map[queue_name] = queue;
return true;

}

}
25 changes: 25 additions & 0 deletions c++/async_task/src/task_queue.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,31 @@ class TaskQueue : public std::enable_shared_from_this<TaskQueue> {
DISALLOW_COPY_AND_ASSIGN(TaskQueue);
};

class GlobalQueue {
public:
// 获取主队列
static const std::shared_ptr<TaskQueue>& get_main_queue();

static bool is_main_queue(const std::shared_ptr<TaskQueue>& queue) { return queue == get_main_queue(); }

// 根据名称获取子队列,如果队列不存在,则返回nullptr
static std::shared_ptr<TaskQueue> get_queue_by_name(const std::string &queue_name);

// 获取默认的全局后台队列
static std::shared_ptr<TaskQueue> get_background_queue();

// 初始化所有队列
static void init_queues(const std::vector<std::string>& queue_names);
// 初始化某个队列
static bool init_queue(const std::string& queue_name);

private:
GlobalQueue() {};
~GlobalQueue() {};
static std::map<std::string, std::shared_ptr<TaskQueue>> _queue_map;
DISALLOW_COPY_AND_ASSIGN(GlobalQueue);
};

}

#endif

0 comments on commit 41f4e74

Please sign in to comment.