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

运行结果


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

相关推荐
持续学习的程序员+11 分钟前
强化学习阶段性总结
人工智能·算法
齐齐大魔王2 分钟前
python爬虫学习进程(四)
爬虫·python·学习
qq_4798754314 分钟前
C++ 模板元编程
java·开发语言·c++
爱装代码的小瓶子17 分钟前
【cpp知识铺子】map与set的底层AVL树
开发语言·数据结构·c++·b树·算法·链表
IT·小灰灰18 分钟前
腾讯HY2.0 Think推理模型深度解析:技术突破、应用场景与实践指南
开发语言·人工智能·python·深度学习·神经网络·算法·数据分析
源代码•宸19 分钟前
100 Go Mistakes(#4 过度使用getter和setter、#5 接口污染)
开发语言·经验分享·后端·golang
修炼地27 分钟前
代码随想录算法训练营第二十八天 | 动态规划理论基础、509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯
c++·算法·动态规划
小南家的青蛙34 分钟前
LeetCode第773题 - 滑动谜题
算法·leetcode·职场和发展
Felven43 分钟前
C. Isamatdin and His Magic Wand!
c语言·数据结构·算法
AndrewHZ1 小时前
【芯芯相印】什么是算法定点化?
pytorch·算法·芯片设计·模型量化·定点化·芯片算法·逻辑电路