Leetcode—1242. 多线程网页爬虫【中等】Plus(多线程)

2024每日刷题(187)

Leetcode---1242. 多线程网页爬虫

实现代码

cpp 复制代码
/**
 * // This is the HtmlParser's API interface.
 * // You should not implement it, or speculate about its implementation
 * class HtmlParser {
 *   public:
 *     vector<string> getUrls(string url);
 * };
 */
class Solution {
public:
    vector<string> crawl(string startUrl, HtmlParser htmlParser) {
        queue<string> q{{startUrl}};
        unordered_set<string> ust{{startUrl}};
        string hostname = getHostName(startUrl);
        vector<thread> threads;
        const int nthreads = std::thread::hardware_concurrency();
        mutex mtx;
        condition_variable cv;

        auto t = [&] {
            while(true) {
                unique_lock<mutex> lock(mtx);
                cv.wait_for(lock, 30ms, [&]() {
                    return q.size();
                });
                if(q.empty()) {
                    return;
                }
                auto cur = q.front();
                q.pop();
                lock.unlock();
                vector<string> urls = htmlParser.getUrls(cur);
                lock.lock();
                for(const string& url: urls) {
                    if(ust.contains(url)) {
                        continue;
                    }
                    if(url.find(hostname) != string::npos) {
                        ust.insert(url);
                        q.push(url);
                    }
                }
                lock.unlock();
                cv.notify_all();
            }
        };

        for(int i = 0; i < nthreads; i++) {
            threads.emplace_back(t);
        }

        for(auto& thread: threads) {
            thread.join();
        }
        return {ust.begin(), ust.end()};
    }
private:
    string getHostName(string& s) {
        int firstIdx = s.find_first_of('/');
        int thirdIdx = s.find_first_of('/', firstIdx + 2);
        return s.substr(firstIdx + 2, thirdIdx - firstIdx - 2);
    }
};

运行结果


之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
程序员Xu29 分钟前
【LeetCode热题100道笔记】二叉树的右视图
笔记·算法·leetcode
笑脸惹桃花1 小时前
50系显卡训练深度学习YOLO等算法报错的解决方法
深度学习·算法·yolo·torch·cuda
阿维的博客日记1 小时前
LeetCode 48 - 旋转图像算法详解(全网最优雅的Java算法
算法·leetcode
GEO_YScsn2 小时前
Rust 的生命周期与借用检查:安全性深度保障的基石
网络·算法
程序员Xu2 小时前
【LeetCode热题100道笔记】二叉搜索树中第 K 小的元素
笔记·算法·leetcode
jingfeng5143 小时前
C++11可变参数模板、emplace系列接口、包装器
开发语言·c++
THMAIL3 小时前
机器学习从入门到精通 - 数据预处理实战秘籍:清洗、转换与特征工程入门
人工智能·python·算法·机器学习·数据挖掘·逻辑回归
芯片智造3 小时前
一文看懂什么是GaN HEMT以及其工艺流程(氮化镓高电子迁移率晶体管)
经验分享·芯片·半导体·晶体管·氮化镓高电子迁移率晶体管
Kevinhbr3 小时前
CSP-J/S IS COMING
数据结构·c++·算法
蕓晨3 小时前
set的插入和pair的用法
c++·算法