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 分钟前
力扣hot100双指针专题解析2(C++)
java·c++·算法·蓝桥杯·双指针
福楠5 分钟前
C++ | 红黑树
c语言·开发语言·数据结构·c++·算法
Trouvaille ~7 分钟前
【Linux】进程间通信(三):共享内存深度剖析与System V IPC机制
linux·c++·操作系统·管道·进程间通信·信号量·system v
丝瓜蛋汤7 分钟前
Proof of the contraction mapping theorem
人工智能·算法
傅泽塔23 分钟前
类和对象(上)
c++
We་ct26 分钟前
LeetCode 58. 最后一个单词的长度:两种解法深度剖析
前端·算法·leetcode·typescript
小袁顶风作案28 分钟前
leetcode力扣——452. 用最少数量的箭引爆气球
学习·算法·leetcode·职场和发展
deep_drink31 分钟前
【经典论文精读(一)】Isomap:非线性降维的全局几何框架(Science 2000)
人工智能·算法·机器学习
mjhcsp1 小时前
莫比乌斯反演总结
c++·算法
喵手1 小时前
Python爬虫零基础入门【第六章:增量、去重、断点续爬·第1节】增量采集:只抓新增/更新(新手也能做)!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·增量、去重·增量采集