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

运行结果


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

相关推荐
凌峰的博客7 分钟前
IEEE Transactions on Network Science and Engineering 期刊投稿经验
经验分享
Jasonakeke23 分钟前
我的编程来时路
java·c++·python
IT从业者张某某31 分钟前
基于DEVC++实现一个控制台的赛车游戏-02-实现赛车游戏
开发语言·c++·游戏
yangSimaticTech35 分钟前
整型数据的转换与比较并不简单
算法
老鼠只爱大米38 分钟前
LeetCode经典算法面试题 #55:跳跃游戏(贪心法、动态规划、BFS等多种实现方案详解)
算法·leetcode·贪心算法·动态规划·bfs·java面试·跳跃游戏
2501_908329851 小时前
C++中的备忘录模式
开发语言·c++·算法
qq_416018721 小时前
C++与机器学习框架
开发语言·c++·算法
左左右右左右摇晃1 小时前
数据结构——红黑树
算法
CoovallyAIHub1 小时前
传感器数据相互矛盾时,无人机蜂群如何做出可靠的管道泄漏检测决策?
算法·架构·无人机