当前位置: 首页 > 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.lryc.cn/news/466196.html

相关文章:

  • RISC-V笔记——内存模型总结
  • 后端常用安全措施
  • 虚拟机数据恢复—通过拼接数据库页碎片的方式恢复数据库的数据恢复案例
  • 【vue】自封组件,基于vue2封装一个弹框组件
  • ES6基础知识
  • 基于Multisim的模拟拔河游戏比赛设计与仿真
  • MyBatis 配置详解
  • 研发运营一体化(DevOps)能力成熟度模型
  • 躺平成长-利用kimi编辑助手帮助自己编程第二天
  • OpenSuse-搭建NFS-Server
  • 【数据结构与算法】之二分查找
  • vue修饰符
  • Oracle里面,with ... as 用法介绍
  • 一个简单的Qt Console Application计算练习程序
  • windows文件拷贝给wsl2的Ubuntu
  • vivado 采用 SSI 器件进行设计
  • Lua环境安装
  • 浏览器控制的无线开关
  • Docker部署SSM项目及避坑指南
  • 多线程代码案例:单例模式/阻塞队列/线程池/定时器
  • Ruby CGI Cookie
  • linux中取消anaconda默认使用base环境
  • 江门中微子到底是做什么的?
  • React源码03 - React 中的更新
  • 【Hive实战】Hive MetaStore升级调研(Mysql)
  • 优化漏洞扫描流程以保障企业数字化业务安全
  • 【大数据算法】一文掌握大数据算法之:大数据算法分析技术。
  • 使用AITemplate和AMD GPU的高效图像生成:结合Stable Diffusion模型
  • 基于yolov10的驾驶员抽烟打电话安全带检测系统python源码+pytorch模型+评估指标曲线+精美GUI界面
  • 虚拟机网络设置为桥接模式