欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > Leetcode—1242. 多线程网页爬虫【中等】Plus(多线程)

Leetcode—1242. 多线程网页爬虫【中等】Plus(多线程)

2024/10/26 5:19:39 来源:https://blog.csdn.net/qq_44631615/article/details/143030798  浏览:    关键词:Leetcode—1242. 多线程网页爬虫【中等】Plus(多线程)

2024每日刷题(187)

Leetcode—1242. 多线程网页爬虫

在这里插入图片描述

实现代码

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

运行结果

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com