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

运行结果


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

相关推荐
哈哈不让取名字3 分钟前
分布式日志系统实现
开发语言·c++·算法
芬加达5 分钟前
leetcode221 最大正方形
java·数据结构·算法
知无不研9 分钟前
实现一个整形栈
c语言·数据结构·c++·算法
夏鹏今天学习了吗11 分钟前
【LeetCode热题100(98/100)】子集
算法·leetcode·深度优先
DuHz13 分钟前
用于汽车应用的数字码调制(DCM)雷达白皮书精读
论文阅读·算法·自动驾驶·汽车·信息与通信·信号处理
李昊哲小课17 分钟前
机器学习核心概念与经典算法全解析
人工智能·算法·机器学习·scikit-learn
风筝在晴天搁浅1 小时前
hot100 437.路径总和Ⅲ
算法
ShineWinsu1 小时前
对于C++:模版初阶的解析
开发语言·c++·面试·笔试·函数··模版
sprintzer1 小时前
1.16-1.25力扣排序刷题
算法·leetcode·职场和发展
Max_uuc1 小时前
【C++ 硬核】告别 Excel 生成数组:利用 constexpr 实现编译期计算查找表 (LUT)
开发语言·c++·excel