import collections
import threading
import queue
from urllib.parse import urlparse
from typing import List
# --- Mock HtmlParser and LeetCode Environment (for local testing) ---
# In a real LeetCode environment, this class would be provided.
# We include a mock here for demonstration purposes.
class HtmlParser:
"""
Mock HtmlParser class to simulate the LeetCode environment.
In a real scenario, this would interact with actual web pages.
"""
def __init__(self, url_map: dict):
self.url_map = url_map
self.call_count = collections.defaultdict(int) # To track calls for testing
def getUrls(self, url: str) -> List[str]:
self.call_count[url] += 1
# Simulate network latency
# import time
# time.sleep(0.01)
return self.url_map.get(url, [])
# Example usage for testing:
# parser = HtmlParser({
# "http://news.yahoo.com/news/1": ["http://news.yahoo.com/news/2", "http://news.yahoo.com/news/3"],
# "http://news.yahoo.com/news/2": ["http://news.yahoo.com/news/3", "http://sports.yahoo.com/sport/1"],
# "http://news.yahoo.com/news/3": [],
# "http://sports.yahoo.com/sport/1": ["http://sports.yahoo.com/sport/2"],
# "http://sports.yahoo.com/sport/2": []
# })
# ---------------------------------------------------------------------
class Solution:
def crawl(self, startUrl: str, htmlParser: 'HtmlParser') -> List[str]:
"""
Multithreaded web crawler to find unique URLs on the same hostname.
"""
# Helper function to extract the hostname from a URL
def get_hostname(url: str) -> str:
# urlparse handles various URL formats and extracts components.
# .hostname returns the domain name (e.g., "news.yahoo.com")
return urlparse(url).hostname
# Determine the target hostname from the startUrl.
# All collected URLs must match this hostname.
target_hostname = get_hostname(startUrl)
# If the startUrl is malformed or doesn't have a hostname, return empty.
if not target_hostname:
return []
# --- Shared Data Structures ---
# 1. visited: A set to keep track of URLs that have been processed or are in the queue.
# This prevents cycles and redundant work.
visited = set()
# 2. result_urls: A list to store the final collected unique URLs.
result_urls = []
# 3. q: A thread-safe queue for URLs that need to be processed.
# queue.Queue handles its own internal locking for put/get operations.
q = queue.Queue()
# 4. shared_data_lock: A lock to protect access to 'visited' and 'result_urls'
# when multiple threads try to modify them concurrently.
shared_data_lock = threading.Lock()
# --- Initial Setup ---
# Add the startUrl to our shared structures and the queue.
with shared_data_lock:
visited.add(startUrl)
result_urls.append(startUrl)
q.put(startUrl) # This increments the queue's internal task counter
# --- Worker Function ---
# This function will be executed by each worker thread.
def worker():
while True:
current_url = None
try:
# Get a URL from the queue. This call blocks until an item is available.
# It also decrements the queue's internal task counter for the task retrieved.
current_url = q.get()
# Check for a sentinel value (e.g., None) to signal thread termination.
if current_url is None:
# If it's a sentinel, mark this "task" as done and exit the loop.
q.task_done()
break
# Attempt to parse the URL using the HtmlParser
urls_found = htmlParser.getUrls(current_url)
# Process each URL found on the current page
for next_url in urls_found:
# Check if the found URL belongs to the same hostname
if get_hostname(next_url) == target_hostname:
# Acquire the lock before modifying shared 'visited' set or 'result_urls' list
with shared_data_lock:
if next_url not in visited:
visited.add(next_url) # Add to visited set
result_urls.append(next_url) # Add to results
q.put(next_url) # Add to queue for further processing
# q.put() increments the queue's internal task counter,
# ensuring q.join() waits for this new task too.
except Exception as e:
# Log or handle exceptions during URL parsing.
# In a production crawler, you might want more robust error handling.
# print(f"Error processing {current_url}: {e}")
pass # Suppress for LeetCode context
finally:
# Crucial: Always call task_done() for the URL retrieved by q.get().
# This tells the queue that the task is complete, allowing q.join() to proceed.
if current_url is not None: # Ensure task_done is not called on None sentinel that broke the loop
q.task_done()
# --- Main Thread Logic ---
# Determine the number of threads. This can be tuned.
# Too few: doesn't fully utilize I/O capabilities. Too many: overhead.
num_threads = 5
threads = []
# Create and start worker threads.
for _ in range(num_threads):
t = threading.Thread(target=worker)
# Set threads as daemon. This means the program will exit even if these
# threads are still running, which is often acceptable for short-lived
# LeetCode solutions. For long-running services, you'd usually t.join() them.
t.daemon = True
threads.append(t)
t.start()
# Block the main thread until all tasks in the queue are completed.
# q.join() waits until all items initially put into the queue, AND
# all items subsequently added by workers, have had q.task_done() called on them.
q.join()
# All reachable URLs have been processed by now.
# Signal worker threads to exit by putting a 'None' sentinel into the queue
# for each worker.
for _ in range(num_threads):
q.put(None)
# At this point, daemon threads will exit when the main program exits.
# If threads were not daemon, you would t.join() them here to ensure they finish.
# Return the collected unique URLs.
return result_urls