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

运行结果


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

相关推荐
Rabitebla42 分钟前
【C++】string 类:原理、踩坑与对象语义
linux·c语言·数据结构·c++·算法·github·学习方法
邪修king1 小时前
UE5 零基础入门第四弹:UMG UI 系统入门,从静态界面到逻辑联动
c++·ui·ue5
小雅痞2 小时前
[Java][Leetcode middle] 167. 两数之和 II - 输入有序数组
java·算法·leetcode
CN-Dust2 小时前
【C++】输入cin例题专题
java·c++·算法
数模竞赛Paid answer3 小时前
2025年MathorCup数学建模A题汽车风阻预测解题文档与程序
算法·数学建模·mathorcup
xin_nai3 小时前
LeetCode热题100(Java)(6)矩阵
java·leetcode·矩阵
Old Uncle Tom8 小时前
OpenClaw 记忆系统 -- 记忆预加载
java·数据结构·算法·agent
会编程的土豆9 小时前
洛谷题单入门1 顺序结构
数据结构·算法·golang
生信碱移9 小时前
PACells:这个方法可以鉴定疾病/预后相关的重要细胞亚群,作者提供的代码流程可以学习起来了,甚至兼容转录组与 ATAC 两种数据类型!
人工智能·学习·算法·机器学习·数据挖掘·数据分析·r语言
智者知已应修善业9 小时前
【51单片机中的打飞机设计】2023-8-25
c++·经验分享·笔记·算法·51单片机