搜狗 workflow 线程模型是什么样的
- User
搜狗 workflow 线程模型是什么样的
- Assistant
搜狗 workflow 线程模型主要采用的是生产者-消费者模型(Producer-Consumer Model)。
具体来说,搜狗 workflow 的线程模型包含两种线程:工作线程(Worker Thread)和任务队列线程(Task Queue Thread)。
工作线程会不断地从任务队列线程中获取任务,并执行任务。当任务队列为空时,工作线程会等待任务队列中有新任务产生。
而任务队列线程则负责接收和存储新的任务,并将其加入任务队列中。当工作线程从任务队列中取走任务后,任务队列线程会再次等待新的任务到来。
这种生产者-消费者模型能够有效地避免线程间的竞争和死锁问题,并保证任务的有序执行。同时,搜狗 workflow 还通过线程池的方式来复用工作线程,进一步提升了系统的性能。
- User
搜狗workflow任务队列代码分析
- Assistant
搜狗workflow的任务队列代码主要集中在Queue和TaskQueue两个类中。下面是它们的主要代码片段:
# Queue类用于存储任务并提供线程安全的方法进行添加、获取、判断队列是否为空等操作 class Queue(object): def __init__(self): self.queue = collections.deque() self.mutex = threading.Lock() self.not_empty = threading.Condition(self.mutex) def put(self, item): with self.mutex: self.queue.append(item) self.not_empty.notify() def get(self, block=True, timeout=None): with self.not_empty: if block: if timeout is None: while not self.queue: self.not_empty.wait() else: endtime = time.time() + timeout while not self.queue: remaining = endtime - time.time() if remaining <= 0.0: raise QueueEmpty self.not_empty.wait(remaining) elif not self.queue: raise QueueEmpty return self.queue.popleft() def empty(self): with self.mutex: return not self.queue # TaskQueue类是搜狗workflow中实际使用的任务队列,继承自Queue类 class TaskQueue(Queue): def __init__(self, maxsize=0): Queue.__init__(self) self._unfinished_tasks = 0 self.maxsize = maxsize self.all_tasks_done = threading.Condition(self.mutex) def put(self, item): with self.mutex: if self.maxsize > 0 and len(self.queue) == self.maxsize: raise QueueFull self.queue.append(item) self._unfinished_tasks += 1 self.not_empty.notify() def task_done(self): with self.mutex: if self._unfinished_tasks <= 0: raise ValueError('task_done() called too many times') self._unfinished_tasks -= 1 if self._unfinished_tasks == 0: self.all_tasks_done.notify_all() def join(self): with self.all_tasks_done: while self._unfinished_tasks: self.all_tasks_done.wait() - User
brpc 协程代码分析
- Assistant
brpc协程主要使用了boost库中的fiber组件来实现。下面是brpc协程部分的核心代码:
class Scheduler { public: explicit Scheduler(int worker_num) :_idle_num{worker_num}, _is_stop{false}, _pool{worker_num} { ::boost::fibers::use_scheduling_algorithm< ::boost::fibers::algo::shared_work >(); // create fibers for (auto& th : _pool) { th = ::boost::fibers::fiber([this]{ this->run(); }); } } void run(); ~Scheduler() { // wait workers stop. stop(); for (auto& th : _pool) { if (th.joinable()) { th.join(); } } } void start_coroutine(Coroutine* co) { std::unique_lock lock{_mutex}; _coroutines.push(co); _cond.notify_one(); } private: // using shared_work, and fibers will according to "fair" to execute. ::boost::fibers::context::active_list_type _ready; std::condition_variable _cond; std::queue<Coroutine*> _coroutines; // Coroutine waiting queue. std::mutex _mutex; std::atomic<int> _idle_num; std::atomic<bool> _is_stop; std::vector<std::thread> _pool; }; void Scheduler::run() { ::boost::fibers::use_scheduling_algorithm< ::boost::fibers::algo::shared_work >(); // run to completion mode while (!_is_stop.load(std::memory_order_acquire)) { ::boost::fibers::fiber::yield(); Coroutine* co = nullptr; { std::unique_lock lock{_mutex}; _cond.wait(lock, [this]{ return !_coroutines.empty() || _is_stop.load(std::memory_order_acquire); }); if (_coroutines.empty()) { if (--_idle_num < 0) { // Idle thread more than thread_num, then stop break; } continue; } co = _coroutines.front(); _coroutines.pop(); } co->resume(); // Coroutine resum if (co->is_alive()) { start_coroutine(co); } else { co->~Coroutine(); // destruct coroutine } } }