Rust 程序设计语言 简体中文版 1.85.0
中需要 size 个元素,预先进行分配比仅仅 Vec::new 要稍微有效率一些, 因为 Vec::new 随着插入元素而重新改变大小。 如果再次运行 cargo check,它应该会成功。 Worker 结构体负责将代码从 ThreadPool 传递给线程 示例 21-14 的 for 循环中留下了一个关于创建线程的注释。这里,我们来看看如何实际创建 线程。标准库提供了 thread::spawn 据类型来管理这种新行为。这个数据结构称为 Worker,这是一个池实现中的常见概念。 Worker 会获取需要运行的代码,并在该 worker 的线程中运行该代码。 想象一下在餐馆厨房工作的员工:员工等待来自顾客的订单,他们负责接单并完成它们。 不同于在线程池中储存一个 JoinHandle<()> 实例的 vector,我们会储存 Worker 结构体的实 例。每一个 Worker 会储存一个单独的 JoinHandle<()> JoinHandle<()> 实例。接着会在 Worker 上实现一个方 法,该方法将闭包发送到已经运行的线程中执行。我们还会赋予每个 worker 一个 id,这样 就可以在日志和调试中区别线程池中的不同 Worker 的实例。 如下是创建 ThreadPool 时会发生的新过程。在通过如下方式设置完 Worker 之后,我们会实现 向线程发送闭包的代码: 1. 定义存放 id 和 JoinHandle<()>0 码力 | 562 页 | 3.23 MB | 10 天前3Tornado 6.5 Documentation
containing only base_url. When a worker fetches a page it parses the links and puts new ones in the queue, then calls task_done to decrement the counter once. Eventually, a worker fetches a page whose URLs have have all been seen before, and there is also no work left in the queue. Thus that worker’s call to task_done decrements the counter to zero. The main coroutine, which is waiting for join, is unpaused and (continued from previous page) if new_url.startswith(base_url): await q.put(new_url) async def worker(): async for url in q: if url is None: return try: await fetch_url(url) except Exception as0 码力 | 272 页 | 1.12 MB | 2 月前3Tornado 6.5 Documentation
containing only base_url. When a worker fetches a page it parses the links and puts new ones in the queue, then calls task_done to decrement the counter once. Eventually, a worker fetches a page whose URLs have have all been seen before, and there is also no work left in the queue. Thus that worker’s call to task_done decrements the counter to zero. The main coroutine, which is waiting for join, is unpaused and if new_url.startswith(base_url): await q.put(new_url) async def worker():async for url in q: if url is None: return try:0 码力 | 437 页 | 405.14 KB | 2 月前3
共 3 条
- 1