Skip to content

Instantly share code, notes, and snippets.

View Kasope's full-sized avatar
🎯
Focusing

Olasunkanmi-Ojo fatima Kasope

🎯
Focusing
View GitHub Profile
import threading, time, random
# Global shared data structures - dangerous to modify from multiple threads
stats = {"total": 0, "completed": 0, "failed": 0}
results = []
def download_with_shared_stats(filename, stats, results):
"""Demonstrate unsafe modification of shared mutable data"""
thread = threading.current_thread().name
@Kasope
Kasope / safe_arguments.py
Created September 22, 2025 12:58
Pass arguments to threads
import threading, time, random
def download_with_options(file_id, filename, size_mb=1, priority="normal", max_retries=3):
"""Simulate downloading a file with various options and retry logic"""
thread = threading.current_thread().name
print(f"[{thread}] Download {file_id}: {filename} ({size_mb}MB, {priority})")
# Calculate download time based on size and priority
base_time = size_mb * 0.3
if priority == "high":
@Kasope
Kasope / custom_thread_downloader.py
Created September 22, 2025 12:55
Subclassing the thread class
import threading
import time
import random
class DownloadThread(threading.Thread):
"""Custom thread class for downloading files with built-in retry logic"""
def __init__(self, url, filename, max_retries=3):
super().__init__(name=f"Downloader-{filename.split('.')[0]}")
self.url = url
@Kasope
Kasope / download_daemon.py
Created September 22, 2025 11:54
Create daemon threads
import threading
import time
def download_monitor():
"""A daemon task that monitors download progress indefinitely"""
while True:
print("Monitoring download queue...")
time.sleep(2)
def download_heartbeat():
@Kasope
Kasope / download_thread_pool.py
Last active September 22, 2025 14:47
Create Thread pools with concurrent.futures
# download_thread_pool.py
import time
import concurrent.futures
import random
def download_file_with_retry(file_info):
"""Simulate downloading a file with retry logic"""
filename, size_mb = file_info
print(f"Starting download: {filename} ({size_mb}MB)")
@Kasope
Kasope / download_queue.py
Last active September 22, 2025 14:46
Thread-safe queues (producer-consumer)
# download_queue.py
import threading
import queue
import time
import random
# Thread-safe queue for download jobs
download_queue = queue.Queue()
def download_producer():
@Kasope
Kasope / safe_download_tracking.py
Created September 22, 2025 11:46
Use locks to fix race conditions
import threading
import time
# Global download statistics and lock to protect them
download_counter = 0
bytes_downloaded = 0
completed_files = 0
stats_lock = threading.Lock()
@Kasope
Kasope / download_race_condition.py
Created September 22, 2025 11:43
Handle race conditions
import threading
import time
# Global download statistics shared by all threads
download_counter = 0
bytes_downloaded = 0
def download_with_tracking(filename, size_mb):
"""Download file and track statistics - UNSAFE"""