当前位置: 首页 > news >正文

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

运行结果

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


http://www.mrgr.cn/news/56412.html

相关文章:

  • 1.Springboot之ApplicationContextListenerConfig
  • 详细尝鲜flutter
  • 【K8s】Kubernetes 证书管理工具 Cert-Manager
  • ArgoWorkflow教程(七)---高效的步骤间文件共享策略
  • Idea-Maven的Setting文件盘配置
  • CSS Grid布局 3行代码 完成等分布局
  • C语言初阶小练习4(不用临时变量交换数值)
  • dolphinscheduler创建工作流及工作流中DataX的使用(简单操作)
  • TikTok账号被限流怎么解决?
  • 【二】企业级JavaScript开发之代码编辑器
  • 什么是表单数据
  • 群晖通过 Docker 安装 Gitea
  • 两个线程交替打印数字
  • 鸿蒙开发:两个重磅更新,鸿蒙版微信要来了!
  • Java学习Day50:唤醒八戒(Excel相关)
  • 中间件之Seata
  • Python酷库之旅-第三方库Pandas(160)
  • Linux基础命令(入门)
  • Java框架之MyBatis Plus
  • linux介绍与基本指令
  • Linux系统基础-进程间通信(2)_命名管道和System V通信
  • 【linux】线程 (三)
  • python虚拟环境安装
  • [LeetCode] 814. 二叉树剪枝
  • github加速 DevSidecar 1.8.8
  • 免费送源码:Java+ssm+MySQL SSM二手物品管理系统 计算机毕业设计原创定制