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);
    }
};

运行结果


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

相关推荐
ShineWinsu几秒前
对于Linux:文件操作以及文件IO的解析
linux·c++·面试·笔试·io·shell·文件操作
hssfscv3 分钟前
软件设计师下午题六——Java的各种设计模式
java·算法·设计模式
跨境麦香鱼4 分钟前
Playwright vs Puppeteer:2026自动化任务与爬虫工具如何选?
运维·爬虫·自动化
北冥有羽Victoria7 分钟前
OpenCLI 操作网页 从0到1完整实操指南
vscode·爬虫·python·github·api·ai编程·opencli
深蓝电商API9 分钟前
反向海淘商品信息爬虫开发实战
爬虫·跨境电商·反向海淘
珂朵莉MM12 分钟前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第3赛季优化题--多策略混合算法
人工智能·算法
罗西的思考19 分钟前
【OpenClaw】通过 Nanobot 源码学习架构---(6)Skills
人工智能·深度学习·算法
枫叶林FYL23 分钟前
【自然语言处理 NLP】7.2 红队测试与对抗鲁棒性(Red Teaming & Adversarial Robustness)
人工智能·算法·机器学习
qiqsevenqiqiqiqi24 分钟前
字符串模板
算法
十五年专注C++开发25 分钟前
Oat++: 一个轻量级、高性能、零依赖的 C++ Web 框架
开发语言·c++·web服务·oatpp